设置上下内边距
<div>
<span>充电 为爱充电</span>
</div>
div {
width: 200px;
padding-top: 50px;
padding-bottom: 50px;
background: #fff;
border: 1px solid pink;
}
span {
font-size: 50px;
}
优点: 简单,只需要设置上下内边距
缺点:父元素不能设置固定高度
line-height
<div>
<p>+ 关注10.1万</span>
</div>
div{
width: 350px;
height: 100px;
background: skyblue;
border-radius: 5px;
}
p {
line-height: 100px;
margin: 0;
}
优点:可设置父元素固定高度
缺点:不太适合多行文字
定位
<div>
<i>en</i>
</div>
div {
position: relative;
background: skyblue;
width: 50px;
height: 200px;
}
i {
height: 50px;
width: 50px;
position: absolute;
top: 50%;
margin-top: -25px;
}
优点: 容易上手
缺点:脱离文档流
flex
<div>
<a href="#">发表评论</a>
</div>
div {
height: 210px;
width: 170px;
display: flex;
flex-direction: column;
justify-content: center;
background: skyblue;
}
优点:简单易懂
缺点:兼容性
table
<ul>
<li><a href="">主站</a></li>
<li><a href="">番剧</a></li>
<li><a href="">游戏中心</a></li>
<li><a href="">直播</a></li>
<li><a href="">会员购</a></li>
<li><a href="">漫画</a></li>
</ul>
ul {
display: table;
background: skyblue;
height: 100px;
}
li {
display: table-cell;
vertical-align: middle;
}
优点:简单
缺点:副作用
grid
ul {
display: grid;
grid-template-columns: repeat(6, 1fr);
align-items: center;
justify-content: center;
background: skyblue;
height: 100px;
}
优点:布局很牛
缺点:兼容性,上手难度高
还是比较适合多行多列布局
伪元素
<div class="main">
<div class="search">
<form action="">
<input type="text" placeholder="技术蛋老师">
<button>按钮</button>
</form>
</div>
</div>
.main {
height: 200px;
background: skyblue;
}
div.search {
display: inline-block;
vertical-align: middle;
}
div.main::after {
content: "";
display: inline-block;
background-color: gold;
height: 100%;
width: 0;
vertical-align: middle;
}
优点:兼容性好
缺点:我太难了