水平垂直居中的方法
一、absolute + 负margin
<div class="out">
<div class="inner">12345</div>
</div>
<style type="text/css">
.out{
position: relative;
width: 300px;
height: 300px;
background: red;
}
.inner{
position: absolute;
width: 100px;
height: 100px;
background: yellow;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
</style>
优点:好理解,兼容性很好。
缺点:需要知道子元素的宽高。
二、absolute + auto margin
<style type="text/css">
.out{
position: relative;
width: 300px;
height: 300px;
background: red;
}
.inner{
position: absolute;
width: 100px;
height: 100px;
background: yellow;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
优点:好理解,兼容性很好。
缺点:需要知道子元素的宽高。
三、absolute + calc
<style type="text/css">
.out{
position: relative;
width: 300px;
height: 300px;
background: red;
}
.inner{
position: absolute;
width: 100px;
height: 100px;
background: yellow;
left: calc(50% - 50px);
top: calc(50% - 50px);
}
</style>
优点:容易理解。
缺点:需要知道子元素的宽高,兼容性一般,需要支持calc。
四、absolute + transform
<style type="text/css">
.out{
position: relative;
width: 300px;
height: 300px;
background: red;
}
.inner{
position: absolute;
background: yellow;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
优点:不需要知道子元素的宽高。
缺点:兼容性一般,需要支持translate。
五、table
<style type="text/css">
.out{
display: table-cell;
width: 300px;
height: 300px;
text-align: center;
vertical-align: middle;
background: red;
}
.inner{
display: inline-block;
background: yellow;
width: 100px;
height: 100px;
}
</style>
优点:兼容性好。
缺点:要对table的使用很熟练。
六、flex
<style type="text/css">
.out{
display: flex;
justify-content: center;
align-items: center;
width: 300px;
height: 300px;
background: red;
}
.inner{
background: yellow;
width: 100px;
height: 100px;
}
</style>
优点:简单。可通过父元素指定子元素的对齐方式,也可通过子元素自己指定自己的对齐方式来实现。
七、grid
//方法一:父元素指定子元素的对齐方式
<style type="text/css">
.out{
display: grid;
align-content: center;
justify-content: center;
width: 300px;
height: 300px;
background: red;
}
.inner{
background: yellow;
width: 100px;
height: 100px;
}
</style>
//方法二:子元素自己指定自己的对齐方式
<style type="text/css">
.out{
display: grid;
width: 300px;
height: 300px;
background: red;
}
.inner{
background: yellow;
width: 100px;
height: 100px;
align-self: center;
justify-self: center;
}
</style>
优点:简单。可通过父元素指定子元素的对齐方式,也可通过子元素自己指定自己的对齐方式来实现。
八、参考
https://developer.mozilla.org/zh-CN/docs/Web/CSS/vertical-align
http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html
http://www.ruanyifeng.com/blog/2015/07/flex-examples.html
http://www.ruanyifeng.com/blog/2019/03/grid-layout-tutorial.html
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!