如何css属性实现各种居中填充方式代码详解
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何css属性实现各种居中填充方式代码详解,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2618字,纯文字阅读大概需要4分钟。
内容图文
![如何css属性实现各种居中填充方式代码详解](/upload/InfoBanner/zyjiaocheng/414/0bcc5709e31c44a3ae2b881f9c76904b.jpg)
margin:0 auto;
也就是将margin-left和margin-right属性设置为auto,从而达到水平居中的效果。
那么其他的办法呢?
line-height
首先介绍文字的水平居中方法:
<p class="wrap">刘放</p>
利用line-height设为height的一样即可:
.wrap{ line-height: 200px;/*垂直居中关键*/ text-align:center; height: 200px; font-size: 36px; background-color: #ccc; }
效果如下:
padding填充
利用padding和background-clip配合实现p的水平垂直居中:
<p class="parent"> <p class="children"> </p> </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;/*居中的关键*/
效果如下:
margin填充
接下来介绍margin填充的方式来实现水平垂直居中。
首先我们还是定义父子p:
<p class="parent"> <p class="children"></p> </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; }
最后得到居中效果如下:
absolute定位
利用position:absolute搭配top,left 50%,再将margin设为负值也可以对p进行水平垂直居中,首先还是需要定义父子p:
<p class="parent"> <p class="children"></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宽度的一半,最后效果图:
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来实现的水平垂直居中的方法。
<p class="parent"> <p class="children">我是通过flex的水平垂直居中噢!</p> </p>
html,body{ width: 100%; height: 200px; } .parent { display:flex; align-items: center;/*垂直居中*/ justify-content: center;/*水平居中*/ width:100%; height:100%; background-color:red; } .children { background-color:blue; }
效果如下:
以上就是如何css属性实现各种居中填充方式代码详解的详细内容,更多请关注Gxl网其它相关文章!
内容总结
以上是互联网集市为您收集整理的如何css属性实现各种居中填充方式代码详解全部内容,希望文章能够帮你解决如何css属性实现各种居中填充方式代码详解所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。