当前第2页 返回上一页
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <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%);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <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;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <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里上下居中怎么弄?的详细内容,更多文章请关注木庄网络博客!
返回前面的内容
相关阅读 >>
css column-rule属性怎么用
css怎么给文字添加边框或字体放大效果(代码详解)
css的冲突是什么
css输入框怎么设置不可编辑
css的sass样式应该怎么使用
css盒子模型是什么意思?
css怎么设置元素一直旋转
css怎么隐藏input
css图片如何设置上边框距离
css3代码和css有不同吗
更多相关阅读请进入《css》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » css里上下居中怎么弄?