标准流中的居中
文字居中
- 水平方向
text-align: center;
- 竖直方向
单行文本居中:让文字的行高等于盒子高。
width: 300px
height: 40px;
text-align: center;
line-height: 40px;
多行文本居中:高度自适应,用内容自动撑开高度,用内边距上下相等撑开空白区域。
width: 300px;
padding: 20px;
盒子居中
- 水平居中
给自身添加宽度,用margin给两边挤出相同的空白。
margin的属性值auto,自动撑开一个最大的边距。
/* 上下外边距为0 左右居中 */
margin: 0 auto;
- 竖直居中
父盒子高度不设置,给父盒子添加上下相同的padding,高度会自适应子盒子的内容高度。
<body>
<div class="outer">
<div class="inner"></div>
</div>
</body>
*{
margin: 0;
padding: 0;
}
.outer{
width: 500px;
padding:50px 0;
border: 1px solid #000;
margin: 100px 200px;
}
.inner{
width: 200px;
height: 100px;
background: skyblue;
margin: 0 auto;
}
非标准流中的居中
在定位中设置盒子的居中
不能使用标准流的方法,只能先左边线居中,自身拽回宽度一半
- 水平方向上
子绝父相,让盒子元素右移父盒子宽度的一半,做外边距设为负的自身宽度的一半。
<body>
<div class="demo1">
<div class="demo2"></div>
</div>
</body>
*{
margin: 0;
padding: 0;
}
.demo1{
width: 400px;
height: 400px;
position: relative;
left: 50px;
top: 50px;
background-color: skyblue;
border: 1px solid #000;
}
.demo2{
width: 100px;
height: 100px;
position: absolute;
left: 50%;
margin-left: -50px;
background-color: yellow;
border: 1px solid #000;
}
- 竖直方向上
与水平方向上差不多,修改bottom属性和margin-bottom就可以