CSS样式中的各种居中方式
1、水平居中
将margin-left和margin-right属性设置为auto,从而达到水平居中的效果。
代码:
margin:0 auto;
2、文字水平垂直居中
利用line-height设为height的一样
代码:
line-height: 200px;/*垂直居中关键*/
height: 200px;
3、利用padding和background-clip配合实现div的水平垂直居中
通过backgroun-clip设置为content-box,将背景裁剪到内容区外沿,再利用padding设为外div减去内div的差的一半
.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;/*居中的关键*/
4、absolute定位
其中的margin中的值为该div宽度的一半
利用position:absolute搭配top,left 50%,再将margin设为负值也可以对div进行水平垂直居中
.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; }
5、text-align居中
将子div的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生效*/ }
图片居中
1、top
1 position:absolute; 2 right:50%; 3 bottom:50%;
2、transform
不需要定宽度的父div实现图片的水平垂直居中
<div class="parent">
<div class="children">
<div class="children-inline">我是水平垂直居中噢!</div>
</div>
</div>
.parent { float: left; width: 100%; height: 200px; background-color: red; } .children { float:left; position:relative; top:50%; left:50%; } .children-inline { position: relative; left: -50%; -webkit-transform : translate3d(0, -50%, 0); transform : translate3d(0, -50%, 0); background-color: black; color:white; }
3、flex水平垂直居中
1 <div class="parent"> 2 3 <div class="children">我是通过flex的水平垂直居中噢!</div> 4 5 </div>
1 html,body{ 2 width: 100%; 3 height: 200px; 4 } 5 .parent { 6 display:flex; 7 align-items: center;/*垂直居中*/ 8 justify-content: center;/*水平居中*/ 9 width:100%; 10 height:100%; 11 background-color:red; 12 } 13 .children { 14 background-color:blue; 15 }
1 水平居中 2 .center-vertical { 3 position: relative; 4 top: 50%; 5 transform: translateY(-50%); 6 } 7 8 9 10 垂直居中 11 .center-horizontal { 12 position: relative; 13 left: 50%; 14 transform: translateX(-50%); 15 }