div垂直居中方法整理

水平居中很简单块级元素:margin:0 auto;内联元素(行内元素): text-align:center,但是垂直居中的办法相对来说麻烦点而且有很多不同的实现方法,今天做一个垂直居中的方法整理。
在这里插入图片描述

结构:

<div class="box">
		<div class="redbox"></div>
</div>

第一种:

.redbox{background-color: red;width: 50px;height:50px;display: inline-block;vertical-align: middle;margin: 0 auto;}
.box{border: saddlebrown 1px solid;width: 500px;height: 300px;margin: 0 auto;text-align: center;}
.box:before{content: "";display: inline-block;width: 0px;height: 100%;position: relative;vertical-align:middle;background-color: #8B4513;}

这办法是需要改div的display,再用父元素创建一个伪div 高度设置为100%,再利用vertical-align 属性,该属性定义行内元素的基线相对于该元素所在行的基线的垂直对齐。

描述
top 把元素的顶端与行中最高元素的顶端对齐
bottom 把元素的顶端与行中最低的元素的顶端对齐。
middle 把此元素放置在父元素的中部。

个人习惯写css不喜欢展开,因为觉得太占行了,如果不太明白试着改一下伪类的高度就明白了。以最高的行内元素为准:
在这里插入图片描述
第二种:

.box{border: saddlebrown 1px solid;width: 500px;height: 300px;margin: 0 auto;}
.redbox{background-color: red;width: 50px;height:50px;margin: 0 auto;position: relative;top: calc(50% - 25px);}

calc()函数用于动态计算长度值

水平居中后,用calc算top值,就是50%-自身的一半,这种方式有很多种实现的办法,例如:

.redbox{background-color: red;width: 50px;height:50px;margin: 0 auto;position:relative;top: 50%;margin-top: -25px;}

不用动态计算,自己再写一个margin-top顶上去就好

.redbox{background-color: red;width: 50px;height:50px;margin: 0 auto;position:relative;top: 50%;transform: translateY(-50%);}

这里要注意translateY(-50%)是自身的50%,也就是-25px

第三种:

.box{border: saddlebrown 1px solid;display: table-cell;width: 500px;height: 300px;margin: 0 auto;vertical-align: middle;}
.redbox{background-color: red;width: 50px;height:50px;margin: 0 auto;}

改变父元素display以表单单元格形式显示,再加个vertical-align: middle,最后也需要子元素水平居中。

第四种:

.box{border: saddlebrown 1px solid;display: flex;align-items: center;width: 500px;height: 300px;margin: 0 auto;}
.redbox{background-color: red;width: 50px;height:50px;margin: 0 auto;}

弹性盒子布局,居中显示

不依靠父元素垂直居中,例如:

比较适合做悬浮窗什么的,如果是提示框就换成文档定位
第一种:

.box{width: 100px;height:100px;background-color: aqua;position: absolute;left: 0px;right: 0px;bottom:0px;top: 0px;margin:auto;} 

第二种

.box{width: 100px;height:100px;background-color: aqua;position: absolute;top:calc(50% - 50px);left:calc(50% - 50px);}

也是根据这个有很多种算top和left的值,例:

.box{width: 100px;height:100px;background-color: aqua;position: absolute;top:50%;left:50%;transform: translateX(-50%) translateY(-50%);}
.box{width: 100px;height:100px;background-color: aqua;position: absolute;top:50%;left:50%;margin-left: -50px;margin-top: -50px;}

上面所说的只要没有改父元素的display属性都可以不依靠父元素达到垂直居中的目的。
以上理解若有错帮忙指出,感谢!
在这里插入图片描述

发布了31 篇原创文章 · 获赞 45 · 访问量 5892

猜你喜欢

转载自blog.csdn.net/weixin_43623808/article/details/103348802
今日推荐