分行内元素和块级元素讨论
<div class="container">
<div class="box1">1</div>
<span class="box2">2</span>
</div>
水平居中
对于行内元素:text-align: center
.container {
text-align: center;
}
对于块级元素:margin: auto;
.box1 {
width: 5vw;
height: 20vh;
margin: auto;
background-color: pink;
}
垂直居中
-
单行文字垂直居中 设置 line-height = height
很常用,主要用于文字的排版 -
块级元素:display: flex
.container {
width: 100vw;
height: 50vh;
display: flex;
align-items: center; /*纵轴方向居中*/
justify-content: center; /*横轴方向居中*/
background-color: gray;
}
- 块级元素:绝对定位 + margin: auto;
.container {
width: 100vw;
height: 50vh;
position: relative;
background-color: gray;
}
.box1 {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
width: 5vw;
height: 20vh;
background-color: pink;
}
- 块级元素:display: table-cell
.father {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.son {
display: inline-block;
}
- 绝对定位(需要提前知道尺寸)
- 块级元素:绝对定位 + transform(不需要提前知道尺寸)
.container {
position: relative;
width: 100vw;
height: 50vh;
background-color: gray;
}
.box1 {
width: 5vw;
height: 20vh;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background-color: pink;
}
- grid布局
.wp {
display: grid;
}
.box {
align-self: center;
justify-self: center;
}
PC端有兼容性要求,宽高固定,推荐absolute + 负margin
PC端有兼容要求,宽高不固定,推荐css-table
PC端无兼容性要求,推荐flex
移动端推荐使用flex