1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 如何实现div盒子水平垂直居中

如何实现div盒子水平垂直居中

时间:2020-11-20 18:45:06

相关推荐

如何实现div盒子水平垂直居中

关于如何使一个小盒子在大盒子中水平垂直居中有很多方法,下面将列举常用的几种:

###html 代码

<div class="parent"><div class="child">DEMO</div></div>

###公共css样式

.parent{width:200px;height:300px;background:#ddd;}.child{background:#666;color:#fff;}

##(1)方法一:

设置margin自动适应,然后设置定位的上下左右都为0,就如四边均衡受力从而实现盒子的居中;

.parent {position:relative;}.child {widht: 100px;height: 100px;position: absolute;margin: auto;top: 0;left: 0;right: 0;bottom: 0;}

##(2)方法二 :定位+位移

使用子绝父相的定位方式,无须知道盒子自身的高度,使用范围较广

.parent{position: relative;}.child{position: absolute;left: 50%;/* 父盒子宽度的50% */top: 50%;/* 父盒子高度的50% */transform: translate(-50%,-50%);/* 子盒子自身宽高的50% */}

##(3)方法三:table-cell+inline-block

将父盒子设置为table-cell(能够使元素呈单元格的样式显示),并设置text-align: center(使内容水平居中);vertical-align: middle(使内容垂直居中);。子盒子设置为inline-block可以使其内容变为文本格式,也可设置宽高;

.parent{display: table-cell;/*使标签元素以表格单元格的形式呈现*/text-align: center; /* 水平居中*/vertical-align: middle;/* 垂直居中 */}.child{display: inline-block;/* 将子盒子设置为行内块级(文本格式)*/}

###(4)方法四:弹性盒子

使用弹性盒子的时候需要给父级设置display:flex;在父元素上设置水平与垂直方向上的排列方式即可;

该方法不需要设置子元素。

.parent{display: flex;justify-content: center;/* 水平方向 居中*/ align-items: center;/* 垂直方向 居中*/}

##总结:

以上几种方式推荐使用弹性盒子,因为在使用定位的时候会使元素脱离文档流出现撑不起父盒子的问题,而在弹性盒子中不会出现这样的问题,而且利用弹性盒子还能解决其他的问题。

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