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的差的一半
- 1 .parent{
- 2 margin:0 auto;
- 3 width:200px;
- 4 height:200px;
- 5 background-color:red;
- 6 }
- 7 .children {
- 8 width: 100px;
- 9 height: 100px;
- 10 padding: 50px;
- 11 background-color: black;
- 12 background-clip:content-box;/*居中的关键*/
4、absolute定位
其中的margin中的值为该div宽度的一半
利用position:absolute搭配top,left 50%,再将margin设为负值也可以对div进行水平垂直居中
- 1 .parent {
- 2 position:relative;
- 3 margin:0 auto;
- 4 width:200px;
- 5 height:200px;
- 6 background-color:red;
- 7 }
- 8 .children {
- 9 position:absolute;
- 10 left:50%;
- 11 top:50%;
- 12 margin:-25px 0 0 -25px ;
- 13 height:50px;
- 14 width:50px;
- 15 background-color: black;
- 16 }
5、text-align居中
将子div的display设为inline-block。
- 1 .parent {
- 2 text-align:center;
- 3 margin:0 auto;
- 4 width:200px;
- 5 height:200px;
- 6 background:red;
- 7 }
- 8 .children {
- 9 positiona;absolute;
- 10 margin-top:75px;
- 11 width:50px;
- 12 height:50px;
- 13 background: black;
- 14 display:inline-block;/*使其父元素text-align生效*/
- 15 }
图片居中
1、top
- 1 position:absolute;
- 2 right:50%;
- 3 bottom:50%;
2、transform
不需要定宽度的父div实现图片的水平垂直居中
- 1 <div class="parent">
- 2
- 3 <div class="children">
- 4
- 5 <div class="children-inline">我是水平垂直居中噢!</div>
- 6
- 7 </div>
- 8
- 9 </div>
- 1 .parent {
- 2 float: left;
- 3 width: 100%;
- 4 height: 200px;
- 5 background-color: red;
- 6 }
- 7 .children {
- 8 float:left;
- 9 position:relative;
- 10 top:50%;
- 11 left:50%;
- 12 }
- 13 .children-inline {
- 14 position: relative;
- 15 left: -50%;
- 16 -webkit-transform : translate3d(0, -50%, 0);
- 17 transform : translate3d(0, -50%, 0);
- 18 background-color: black;
- 19 color:white;
- 20 }
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 }