今天老大随口问了这个问烂了的问题,我只回答了两种,好吧,仍是老老实实总结下来增强下记忆吧。bash
一:定位+边距(固定宽高度适用)布局
<div class="container">
<div class="inner"></div>
</div>
复制代码
.container {
width: 400px;
height: 400px;
position: relative;
background-color: yellow;
}
.inner {
position: absolute;
height: 200px;
width: 200px;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
background-color: red;
}
复制代码
二:定位+transform(不固定宽高也适用)flex
.container {
width: 400px;
height: 400px;
background-color: yellow;
position: relative;
}
.inner {
height: 200px;
width: 200px;
background-color: red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
复制代码
三:flex布局spa
.container {
width: 400px;
height: 400px;
background-color: yellow;
display: flex;
align-items: center;
justify-content: center;
}
.inner {
height: 200px;
width: 200px;
background-color: red;
}
复制代码
四:table布局code
<div class="container">
<div class="outter">
<div class="inner"></div>
</div>
</div>
复制代码
.container {
width: 400px;
height: 400px;
background-color: yellow;
display: table;
}
.outter {
background-color: red;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.inner {
height: 100px;
width: 100px;
display: inline-block;
background-color: white;
}
复制代码
五:杂谈orm
以上为比较好用的块级元素居中方案,别的一些细节以下:string
行内元素垂直居中:it
一、父元素等值paddingio
二、子元素line-height等于父元素高度table
块级元素水平居中:
margin: 0 auto
复制代码
基础仍是要打好的,知道不行,熟练也不够,但愿刻在脑子里,造成条件反射才足够。