什么是块级元素:会自动占据一定矩形空间,可以通过设置高度、宽度、内外边距等属性,来调整的这个矩形的样子。
常见的块级元素:div、ul、li、dl、dt、dd、p、h1-h6、blockquote
什么是行内元素:没有自己独立的空间,它是依附于其他块级元素存在的,因此,对行内元素设置高度、宽度、内外边距等属性,都是无效的
常见的行内元素:a、b、span、img、input、strong、select、label、em、button、textarea
行内元素水平垂直居中方法
1.水平居中:给父级设置
div{
text-align : center;
}
2垂直居中:
div {
height: 100px;
line-height: 100px;
}
3.既要水平居中又要垂直居中:
div {
height: 100px;
text-align: center;
line-height: 100px;
}
块级元素水平垂直居中方法
html
<div class="box1">
<div class="box2">水平垂直居中</div>
</div>
需要知道子元素的宽高
1.Margin为负值
父级节点相对定位,居中块绝对定位
top:50%; left:50%;
margin-top: -height/2; margin-left: -width/2
.box1 {
width: 200px;
height: 200px;
background-color: #eee;
position: relative;
}
.box2 {
position: absolute;
width: 100px;
height: 100px;
background-color: red;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px
}
2.绝对定位
父级节点相对定位,居中块绝对定位,top:0;left:0;right:0;bottom:0;margin:auto;
.box1 {
width: 200px;
height: 200px;
background-color: #eee;
position: relative;
}
.box2 {
position: absolute;
width: 100px;
height: 100px;
background-color: red;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
3.absolute + calc()函数
父级节点相对定位,居中块绝对定位
left: calc(50% - width/2);
top: calc(50% -height/2;
.box1 {
width: 200px;
height: 200px;
background-color: #eee;
position: relative;
}
.box2 {
position: absolute;
width: 100px;
height: 100px;
background-color: red;
left: calc(50% - 50px);
top: calc(50% - 50px);
}
不需要知道子元素的宽高
1.Flex布局
父元素设置,主轴和交叉轴均为center
.box1 {
display: flex;
justify-content: center; //水平居中
align-items: center; //垂直居中
}
2.利用css3的属性Transform
父级节点相对定位,居中块绝对定位
子元素:top:50%; left:50%; transform: translate(-50%, -50%)
.box1 {
width: 200px;
height: 200px;
background-color: #eee;
position: relative;
}
.box2 {
position: absolute;
background-color: red;
top: 50%;
left: 50%;
transform: translate(-50%, -50%)
}