行内及块级元素在块级元素内实现水平垂直居中
1、行内元素
<div>
<span>This is a text</span>
</div>
div{
height: 200px;
width: 200px;
background-color: lightblue;
}
(1)方法一
给div中设置line-height为当前块级元素高度,设置text-align:center,即可实现水平垂直居中;
div{
height: 200px;
width: 200px;
background-color: lightblue;
line-height: 200px;
text-align: center;
}
效果如下
(2)方法二
利用伸缩盒布局给div设置如下属性:
div{
height: 200px;
width: 200px;
background-color: lightblue;
display: flex;
justify-content: center;
align-items: center;
}
效果同上。
2、块级元素
<div id="outer">
<div id="inner"></div>
</div>
#outer{
width: 200px;
height: 200px;
background-color:blue;
}
#inner{
width: 100px;
height: 100px;
background-color: aquamarine;
}
(1)方法一
利用定位布局,给父元素相对定位,子元素绝对定位,left,top,bottom,right都为0,且子元素magin:auto
#outer{
width: 200px;
height: 200px;
background-color:blue;
position: relative;
}
#inner{
width: 100px;
height: 100px;
background-color: aquamarine;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
效果如下:
还可以在父元素设置相对定位,子元素设置绝对定位的基础上,设置子元素向左和向上偏移50%,这时块级子元素位于父元素的右下,那么再向上向左偏移子元素本身宽高的一半即可
#inner{
width: 100px;
height: 100px;
background-color: peachpuff;
position: absolute;
top: 50%;
left: 50%;
margin-top:-50px;
margin-left:-50px ;
}
(2)方法二
和行内元素一样块级元素也可以使用伸缩盒布局来实现水平垂直居中,只给父元素设置如下属性即可
#outer{
width: 200px;
height: 200px;
background-color: blue;
display: flex;
justify-content: center;
align-items: center;
}
还可以在父元素中只设置 display: flex;在子元素中设置 margin: auto;来实现
#outer{
width: 200px;
height: 200px;
background-color: blue;
display: flex;
}
#inner{
width: 100px;
height: 100px;
background-color: aquamarine;
margin: auto;
}
效果同上。