css上下居中的实现方法:1、将单行的行内元素设置行高等于盒子高;2、将多行的行内元素使用给父元素设置“display:table-cell;和vertical-align: middle;”即可。

css里上下居中也就是垂直居中,css中按元素可以分为三种垂直居中方式,分别是单行的行内元素,多行的行内元素以及块元素的垂直居中,下面将做详细介绍。
单行的行内元素
只需要设置单行行内元素的"行高等于盒子的高"即可;
<style>
#father {
width: 500px;
height: 300px;
background-color: skyblue;
}
#son {
background-color: green;
height: 300px;
}
</style>
<div id="father">
<span id="son">我是单行的行内元素</span>
</div>效果:
立即学习“前端免费学习笔记(深入)”;

多行的行内元素
使用给父元素设置display:table-cell;和vertical-align: middle;即可;
<style>
#father {
width: 500px;
height: 300px;
background-color: skyblue;
display: table-cell;
vertical-align:middle;
}
#son {
background-color: green;
}
</style>
<div id="father"><span id="son">我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素</span>
</div>
效果:
立即学习“前端免费学习笔记(深入)”;

块级元素
方案一:使用定位
首先设置父元素为相对定位,再设置子元素为绝对定位,设置子元素的top: 50%,即让子元素的左上角垂直居中;
定高度:设置绝对子元素的 margin-top: -元素高度的一半px; 或者设置transform: translateY(-50%);
<style>
#father {
width: 500px;
height: 300px;
background-color: skyblue;
position: relative;
}
#son {
height: 100px;
background-color: green;
position: absolute;
top: 50%;
margin-top: -50px;
}
</style>
<div id="father">
<div id="son">我是块级元素</div>
</div>不定高度:利用css3新增属性transform: translateY(-50%);
<style>
#father {
width: 500px;
height: 300px;
background-color: skyblue;
position: relative;
}
#son {
width: 100px;
background-color: green;
position: absolute;
left: 50%;
transform: translateY(-50%);
}
</style>
<div id="father">
<div id="son">我是块级元素</div>
</div>效果:
立即学习“前端免费学习笔记(深入)”;

方案二:使用flexbox布局实现(高度定不定都可以)
使用flexbox布局,只需要给待处理的块状元素的父元素添加属性 display: flex; align-items: center;
<style>
#father {
width: 500px;
height: 300px;
background-color: skyblue;
display: flex;
align-items: center;
}
#son {
width: 100px;
height: 100px;
background-color: green;
}
</style>
<div id="father">
<div id="son">我是块级元素</div>
</div>效果:

相关教程:CSS视频教程
以上就是css里上下居中怎么弄?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号