1、垂直居中显示
<body>
<div class="box"></div>
</body>
1. 已知盒子box宽高(200px)
.box{
width: 200px;
height: 200px;
background-color: lightblue;
position: absolute;
top:50%;
left: 50%;
margin-left: -100px;//盒子宽度的一半
margin-top: -100px;//盒子高度的一半
}
因为定位是相对于盒子左上角,所以,要让盒子垂直居中必须往左和往上各减去宽高的一半;
此方法仅适用于高宽固定,高宽发生变化就需要多处进行更改;
2. 灵活适用高宽发生变化的情况
.box{
width: 200px;
height: 200px;
background-color: blue;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
无论宽高怎么变化都是垂直居中;
3. 宽高未知的情况(使用flex布局)
<body>
<div class="father">
<div class="box">
<p>hhhhhhhhhhhhhhhh</p>
<p>hhhhhh</p>
<p>hhhhhhhhhhh</p>
<p>jkkk</p>
</div>
</div>
</body>
//父元素
.father{
width: 500px;
height: 200px;
background-color: pink;
display: flex;
justify-content: center;
align-items: center;
}
//目标盒子
.box{
background-color: #0000FF;
}
可以在目标盒子随意填充内容,一直保持垂直居中
2、双飞翼布局
1.写一个左中右布局,左右宽度为200px,中间自适应,且优先加载中间块
<body>
<div class="container">
<div class="center">中</div>
</div>
<div class="left">左</div>
<div class="right">右</div>
</body>
<style type="text/css">
*{
margin: 0;padding: 0;
}
body>div{
float: left;
}
.center{
background-color: orange;
margin: 0 200px;
}
.container{
width: 100%;
}
.left{
width: 200px;
background-color: blue;
margin-left: -100%;
}
.right{
width: 200px;
background-color: seagreen;
margin-left: -200px;
}
</style>
3、清除浮动
三个盒子都左浮动,给父元素加边框,内容因为浮动无法填充
1.clear:both
<body>
<div class="father">
<div class="left item"></div>
<div class="center item"></div>
<div class="right item"></div>
<div class="clear"></div>
</div>
</body>
在最后一个浮动元素后添加一个空盒子
.clear{
clear:both;
}
清除后样式
2.overflow:hidden
不需要添加多余的div,直接给父元素添加overflow:hidden;
.father{
border: 15px solid #8B0000;
overflow: hidden;
}
3.使用after伪类
最最最常用的一种方式
.father:after{
content: " ";
clear: both;
display: table;
}