900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > div水平居中和垂直居中

div水平居中和垂直居中

时间:2023-05-13 02:39:42

相关推荐

div水平居中和垂直居中

在前端开发时,经常会遇到需要居中的情形,居中分2种情况,一个是水平居中,一个是垂直居中,总结一下用到的方法。

水平居中实现

margin:0 auto

auto表示外边距左右距离相同即可实现水平居中的效果

垂直居中实现

1、最常用到的一种方式是根据偏移量来实现

<style>*{margin: 0;padding: 0;}.content{position: relative;width: 300px;height: 300px;background-color: #000;margin: 300px auto;}.beat{width: 100px;height: 100px;background-color: #ff0000;position: absolute;left:50%;top:50%;margin-top: -50px;margin-left: -50px;}</style><div class="content"><div class="beat"></div></div>

红色方块位于黑色方块的中心位置,实现了垂直居中效果

left,top分别设置50%,红色方块的起始点位于垂直居中的位置,效果如下图:

想要实现方块内部中心点垂直居中,还要加上偏移量,margin-top的值为红色框heigh/2,margin-left的值为红色框width/2。

2、让div块里的多行文字垂直居中,可以用table和table-cell来实现

<style>*{margin: 0;padding: 0;}.content{width: 300px;height: 300px;background-color: #000;margin: 300px auto;color: #fff;display: table;text-align: center;}.content p{display: table-cell;height: 100px;vertical-align: middle;}</style><div class="content"><p>垂直居中是布局中十分常见的效果之一垂直居中是布局中十分常见的效果之一垂直居中是布局中十分常见的效果之一垂直居中是布局中十分常见的效果之一</p></div>

display: table使块状元素成为一个块级表格,display: table-cell;子元素设置成表格单元格,vertical-align: middle;使表格内容居中显示,即可实现垂直居中的效果

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。