版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/Ruffaim/article/details/82711974
在掘金看到一篇有关文章,自己做整理,方便在工作上用到查阅。
需要实现的效果
根据宽度高度是否固定
- absolute + 负margin
- absolute + margin auto
- absolute + calc
根据宽度高度不固定
- absolute + transform
- lineheight
- writing-mode
- table
- css-table
- flex
- grid
# absolute + 负margin
已知有两个固定宽度高度的div .fa和.sub,要求.sub在.fa中水平居中对齐
<body>
<div class="fa">
<div class="sub"></div>
</div>
</body>
使用传统的 position: relative和 position: absolute ,即子绝父相
<style type="text/css">
.fa{
width: 200px;
height: 200px;
border:1px solid;
position: relative;
}
.sub{
width: 100px;
height: 100px;
background-color: skyblue;
position: absolute;
left: 50px;
top: 50px;
}
</style>
使用absolute 和 -margin 效果等同前者
<style type="text/css">
.fa{
width: 200px;
height: 200px;
border:1px solid;
position: relative;
}
.sub{
width: 100px;
height: 100px;
background-color: skyblue;
position: absolute;
left:0;
top:0;
margin-left: 50px;
margin-top: 50px;
}
</style>
这一类写法效果最好最常用,浏览器兼容性最佳,但是需要要求元素高度固定。
# absolute + margin auto
同样作用于高度宽度固定的元素,在子元素 position: absolute 时将”left”, “top”, “right” 以及 “bottom” 设为0,给予margin:auto。
<style type="text/css">
.fa{
width: 200px;
height: 200px;
border:1px solid;
position: relative;
}
.sub{
width: 100px;
height: 100px;
background-color: skyblue;
position: absolute;
left:0;
top:0;
bottom: 0;
right: 0;
margin:auto;
}
</style>
浏览器兼容性很好,支持所有现代浏览器。
# absolute + calc
css3 calc属性原本是用于在css样式中做四则运算,在已经高度的情况下可以使元素垂直水平对齐,通过计算得到absolute相对的值。
<!-- 单个div -->
<style type="text/css">
.fa {
position: absolute;
left: calc(50% - 100px);
top: calc(50% - 100px);
width: 200px;
height: 200px;
border: 1px solid red;
}
</style>
<body>
<div class="fa">
</div>
</body>
通过一张图可以清楚地看出来,整张图片为浏览器窗口对象,通过calc函数计算出当前div的absolute相对位置。
可以结合calc函数实现宽高div中的垂直水平对齐
<!-- div中垂直居中-->
<style type="text/css">
.fa {
position: relative;
width: 200px;
height: 200px;
background-color:pink;
}
.sub {
position: absolute;
width: 100px;
height: 100px;
background-color: skyblue;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
</style>
<body>
<div class="fa">
<div class="sub"></div>
</div>
</body>
效果如图
因为是CSS3标准,所以兼容性还不是非常好,可以参照下图做对比。
周末接着更新。