一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第6天,点击查看活动详情。
前情提要
- 主要的html布局如下:
<body>
<div class="container">
<div class="box"></div>
</div>
</body>
- 定宽高和不定宽高指的是子元素的宽高,也就是dom元素中class为box的div
- 必备知识点
- 相对定位:是相对自己而言进行位置的移动。不会脱离文档流,原先的位置会空出来。
- 绝对定位:如果各级父级元素都没有定位,则相对body进行绝对定位。各级父级任意有一个定位则相对其进行绝对定位。如果有多个父级有定位信息,则采用就近原则。会脱离文档流,原先的位置会被其他元素占用。
- 方法:
- 绝对定位 + 负magin值
- 绝对定位 + margin
- 绝对定位 + transform
- flex
- grid
- table-cell + vertical-align + inline-block
- flex变异
绝对定位 + 负magin值
.box {
height: 200px;
width: 200px;
background-color: red;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
如图:
绝对定位 + margin
.box {
height: 200px;
width: 200px;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
background-color: yellow;
}
如图:
绝对定位 + transform
- 此时定宽高与不定宽高都可以
.box{
height: 200px;
width: 200px;
background-color: yellow;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
如图:
flex
- 有宽高和无宽高是一样的flex 父元素必须要有高
.container{
height: 500px;
width: 500px;
background-color: yellow;
display: flex;
justify-content: center;
align-items: center;
}
.box{
height: 200px;
width: 200px;
background-color: red;
}
如图:
grid
- 有宽高和无宽高是一样的 grid 父元素必须要有宽高
.container{
height: 500px;
width: 500px;
background-color: yellow;
display: grid;
}
.box{
width: 50px; // 如果元素内部没有内容的化页面上什么都没有,此时暂时指定宽高来代替内容
height: 50px; // 如果元素内部没有内容的化页面上什么都没有,此时暂时指定宽高来代替内容
background-color: red;
margin: auto;
}
如图:
table-cell + vertical-align + inline-block
- 有宽高和无宽高差不多,父元素必须要有宽高 table-cell + vertical-align + 直接设置成这个inline-block有宽高无宽高一样。设置margin: auto则时有宽高
.container{
height: 500px;
width: 500px;
background-color: yellow;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.box{
height: 200px;
width: 200px;
background-color: red;
/* margin: auto; */
display: inline-block;
}
如图:
flex变异
- 定宽高不定宽高都可以
.container{
height: 500px;
width: 500px;
background-color: yellow;
display: flex;
}
.box{
/* height: 200px;*/
/* width: 200px; */
background-color: red;
margin: auto;
}
如图: