Article directory
Method 1. line-height (only for text)
css:
<style>
div {
width: 300px;
height: 300px;
border: 1px solid black;
}
span {
line-height: 300px;
}
</style>
html:
<div>
<span>hello</span>
</div>
Effect:
Note: This method only works for horizontal centering of text classes.
If you replace the label of the above sub-element with a label span
, you will find that the sub-element cannot be centered and will be slightly lower: at this time, we only need to set the margin value of the p tag to 0 (because the p tag has a margin value by default)p
Method 2: flex layout
css:
<style>
.father {
/*第一步:将父元素转换为flex布局 */
display: flex;
/*第二步:设置align-item垂直对齐*/
align-items: center;
width: 300px;
height: 300px;
border: 1px solid black;
}
.son {
width: 100px;
height: 100px;
background-color: coral;
}
</style>
html:
<div class="father">
<div class="son"></div>
</div>
Effect:
Disadvantage: Compatibility is not good enough (compatible with IE9 and above)
Method 3: Positioning + transform
css:
<style>
.father {
/*第一步:将父元素设置相对定位 */
/*解释:若不给父元素添加定位属性,下面的子元素会相对于浏览器窗口定位*/
position: relative;
width: 300px;
height: 300px;
border: 1px solid black;
}
.son {
/*第二步:将子元素设置绝对定位*/
position: absolute;
/*第三步:子元素向下挪动50%(相对于父元素高度)*/
top: 50%;
/*第四步:将子元素沿Y轴向上位移50%(相对于子元素自身高度)*/
transform: translateY(-50%);
width: 100px;
height: 100px;
background-color: coral;
}
</style>
html:
<div class="father">
<div class="son"></div>
</div>
Effect:
Some friends may not understand this method. I will explain it to you with a legend (if you understand, please skip it):
Disadvantage: Because of setting positioning, it is out of the document flow, which may cause layout conflicts with other elements (such as: with other elements overlap)
Method 3: table-cell
css:
<style>
.father {
/*第一步:设置父元素为table-cell布局*/
display: table-cell;
/*第二步:设置垂直对齐(注意:这里的值是middle,不是center!)*/
vertical-align: middle;
width: 300px;
height: 300px;
border: 1px solid black;
}
.son {
width: 100px;
height: 100px;
background-color: coral;
}
</style>
html:
<div class="father">
<div class="son"></div>
</div>
Effect: