php全局居中代码,如何css属性实现各种居中填充方式代码详解

首先是水平居中,最简单的办法当然就是margin:0 auto;

也就是将margin-left和margin-right属性设置为auto,从而达到水平居中的效果。

那么其他的办法呢?

line-height

首先介绍文字的水平居中方法:

刘放

利用line-height设为height的一样即可:.wrap{

line-height: 200px;/*垂直居中关键*/

text-align:center;

height: 200px;

font-size: 36px;

background-color: #ccc;

}

效果如下:

d19efb51eb8e4ea6083dae66758ad495.png

padding填充

利用padding和background-clip配合实现p的水平垂直居中:

通过backgroun-clip设置为content-box,将背景裁剪到内容区外沿,再利用padding设为外p减去内p的差的一半,来实现:.parent{

margin:0 auto;

width:200px;

height:200px;

background-color:red;

}

.children {

width: 100px;

height: 100px;

padding: 50px;

background-color: black;

background-clip:content-box;/*居中的关键*/

效果如下:

9cfbef8fe420ac407aded44246aa2bfe.png

margin填充

接下来介绍margin填充的方式来实现水平垂直居中。

首先我们还是定义父子p:

这里我们利用将子p的margin-top设置为父p高度减去子p高度的一半,然后再通过overflow设置为hidden来触发父p的BFC,LESS代码如下:@parentWidth:200px;

@childrenWidth:50px;

.parent {

margin:0 auto;

height:@parentWidth;

width:@parentWidth;

background: red;

overflow:hidden;/*触发BFC*/

}

.children {

height:@childrenWidth;

width:@childrenWidth;

margin-left:auto;

margin-right:auto;

margin-top: (@parentWidth - @childrenWidth) / 2;

background:black;

}

最后得到居中效果如下:

4cf55e522df2265cab10f7ef1a92916b.png

absolute定位

利用position:absolute搭配top,left 50%,再将margin设为负值也可以对p进行水平垂直居中,首先还是需要定义父子p:

然后设置相应的css:.parent {

position:relative;

margin:0 auto;

width:200px;

height:200px;

background-color:red;

}

.children {

position:absolute;

left:50%;

top:50%;

margin:-25px 0 0 -25px ;

height:50px;

width:50px;

background-color: black;

}

其中的margin中的值为该p宽度的一半,最后效果图:

fe2033a0e55a4dc30cb5a5adb5591c5b.png

text-align居中

众所周知,text-align可以使得一个p中的内容水平居中。但是如果是要将该p中的子p居中呢?可以将子p的display设为inline-block。.parent {

text-align:center;

margin:0 auto;

width:200px;

height:200px;

background:red;

}

.children {

positiona;absolute;

margin-top:75px;

width:50px;

height:50px;

background: black;

display:inline-block;/*使其父元素text-align生效*/

}

flex居中

最后来介绍一下CSS3中的display:flex来实现的水平垂直居中的方法。

我是通过flex的水平垂直居中噢!

width: 100%;

height: 200px;

}

.parent {

display:flex;

align-items: center;/*垂直居中*/

justify-content: center;/*水平居中*/

width:100%;

height:100%;

background-color:red;

}

.children {

background-color:blue;

}

效果如下:

f8385e4f4848ad2808dc0efc0fabb217.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值