一、有几种方法让一个盒子水平垂直居中(最常问的一个)
<div class="box">
<div class="box1"></div>
</div>
1.定位+transform
用transform的好处就是不用去算本身的宽度一半
<style>
.box {
width: 200px;
height: 200px;
background-color: blue;
position: relative;
}
.box1 {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
</style>
效果:
2.用定位加margin
这种就比较简单直接定位左上各五十再减去自身宽度的一半,相比上面那个要算具体值
<style>
.box {
width: 200px;
height: 200px;
background-color: blue;
position: relative;
}
.box1 {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
</style>
3.用定位+margin自适应
<style>
.box {
width: 200px;
height: 200px;
background-color: blue;
position: relative;
}
.box1 {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
4.子级display:flex
内容对齐(justify-content)属性应用在弹性容器上,把弹性项沿着弹性容器的主轴线(main axis)对齐。
align-items
设置或检索弹性盒子元素在侧轴(纵轴)方向上的对齐方式。
<style>
.box {
width: 200px;
height: 200px;
background-color: blue;
display: flex;
justify-content: center;
align-items: center;
}
.box1 {
width: 100px;
height: 100px;
background-color: red;
}
</style>
5.父级display:table-cell
父级必须设宽高,子级必须是行内块元素(不推荐使用)
<style>
.box {
width: 200px;
height: 200px;
background-color: blue;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.box1 {
width: 100px;
height: 100px;
background-color: red;
display: inline-block;
}
</style>
二、清除浮动的五种方法
1.伪对象法
.clearfloat:after{
content:"";
display:block;
clear:both;
height:0;
overflow:hidden;
}
.clearfloat{
zoom:1;
}
2.父元素加clear:both;
3.父元素加overflow:hidden;
4.空div法
浮动元素的后面,加一个 <div class="clear"></div>
添加样式.clear{clear:both;}
5.父元素加height(父元素高已知)
6.父元素跟随子元素一起浮动
三、 隐藏一个元素的3种方法与区别
display:none; 不占位置
visibility:hidden;占位置
opacity:0; 占位置