块级元素如何在父元素中水平垂直居中
1) 父元素position
1. 父元素相对定位,子元素绝对定位,子元素margin:auto;top:0;left:0;bottom:0;right:0;
2. 父元素相对定位,子元素绝对定位,子元素left:50%,top:50%;margin-left:-子元素一半的宽度;margin-top: - 子元素一半的高度
2) 父元素display
3. 父元素display:flex; justify-content:center; align-items:center,子元素自动居中 (伸缩盒布局)
如何让元素使用margin:0 auto,水平居中
只对块级元素生效,所以margin:0 auto的用法分为三种,分别为
1、块级元素:div、h1~h3、ul
/对于块级元素,只需要设置width/
div{
width: 200px;
background-color: #ccc;
margin:0 auto;
}
2、行内元素:span、a
/*对于行内元素,需要先设置为块级元素,再加宽度*/
span{
display: block;
width: 100px;
background-color: red;
margin:0 auto;
}
3、行内块元素:button、img、input、textarea
/*对于行内块级元素,需要设置为块级元素,可以不用设置宽度*/
input{
display: block;
margin:0 auto;
}