居中
1. 文字、内联元素、内联块元素在父元素居中
-
文字、内联元素居中。
父元素设置:
text-align: center;`` line-height: height;
.parent{ width: 500px; height: 400px; background-color: cadetblue; margin: 0 auto; text-align: center; line-height: 400px; } .child{ background-color: red; border: 1px solid black; }
<div class="parent"> <span class="child">我是内联元素</span> </div>
-
内联块元素在父元素居中:
给该元素设置
vertical-align:middle
(文字和内联元素居中对齐),为其父元素中设置after伪类,高度为100%并设置居中对齐,内联块元素在其父元素中垂直居中。.parent{ width: 300px; height: 200px; background-color: cadetblue; margin: 0 auto; /* 水平居中 */ text-align: center; } /* 垂直方向 */ .parent::after{ display: inline-block; content: ""; height: 200px; vertical-align: middle; } span{ display: inline-block; width: 150px; height: 100px; background-color: red; border: 1px solid black; /* 内联元素内容居中 */ text-align: center; line-height: 100px; }
<div class="parent"> <span>我是内联块元素</span> </div>
2. 区块元素在父元素中居中
-
margin:auto
,只能将区块元素相对于包含块的边缘水平居中(要求子元素比父元素小,且只能做水平方向的居中)。.parent{ width: 500px; height: 400px; background-color: cadetblue; margin: 0 auto; } .child{ width: 200px; height: 150px; background-color: red; border: 1px solid black; margin: auto; }
-
设置为参照父元素的绝对定位,并将left或top的值设置为50%,然后将变形transform的位置函数
transform: translate(-50%, -50%);
,translate中的百分比为自己宽高的百分比.parent{ width: 500px; height: 400px; background-color: cadetblue; margin: 0 auto; position: relative; } .child{ width: 200px; height: 150px; background-color: red; border: 1px solid black; position: absolute; /* 相对父元素宽高的50% */ left: 50%; top: 50%; /* 相对自己宽高的50% */ transform: translate(-50%, -50%); }
-
将上面的居中方法中的变形函数替换成margin:margin-left:-1/2自己宽或margin-top:-1/2自己高,因为margin的所有方向百分比为父元素的宽度,因为这里不能用百分比。
.parent{ width: 500px; height: 400px; background-color: cadetblue; margin: 0 auto; position: relative; } .child{ width: 200px; height: 150px; background-color: red; border: 1px solid black; position: absolute; /* 相对父元素宽高的50% */ left: 50%; top: 50%; /* 相对自己宽高的50% */ margin-left: -100px; margin-top: -75px; }
-
设置为参照父元素的绝对定位或固定定位,将左右或上下偏移值设置为0,并将左右或上下margin设置为auto
要求:子元素不能比父元素大。
.parent{ width: 500px; height: 400px; background-color: cadetblue; margin: 0 auto; position: relative; } .child{ width: 200px; height: 150px; background-color: red; border: 1px solid black; position: absolute; margin: auto; left: 0; right: 0; top: 0; bottom: 0; }
<div class="parent"> <div class="child"></div> </div>
如果子元素比父元素大,则失效:
.child{ width: 600px; /*width调整为600px*/ height: 150px; background-color: red; border: 1px solid black; position: absolute; margin: auto; left: 0; right: 0; top: 0; bottom: 0; }
3. 练习
做一个宽高300背景为灰色的div块,固定定位在页面右下角,并为其设置一个子元素son,绝对定位在其正中心。
body{
height: 10000px;
width: 100%;
}
.parent{
width: 300px;
height: 300px;
background-color: gray;
position: fixed;
bottom: 0px;
right: 0px;
}
.son{
width: 100px;
height: 100px;
background-color: hotpink;
/* 相对于父元素 */
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
<div class="parent">
<div class="son"></div>
</div>