宽高不确定div居中
宽高不定的div水平垂直居中在前端页面布局中经常用到,它能够根据当前页面的大小做到自适应,使页面展示更协调;由于比较重要,因此在前端面试的时候此知识点会经常被问到。
- 水平垂直居中方式一:使用flex布局:
<body>
<div id="div1">
<div id="subDiv1"></div>
</div>
</body>
<style>
html,body{
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#div1{
border: 1px red solid;
height: 100%;
width: 100%;
/*方法一: flex布局*/
display: flex;
align-items: center;/*垂直居中*/
justify-content: center;/*水平居中*/
}
#subDiv1{
width: 300px;
height: 400px;
border: 1px solid green;
}
</style>
- 水平垂直居中方式二:absolute定位 + transform:
#div1{
border: 1px red solid;
height: 100%;
width: 100%;
position: relative;
}
#subDiv1{
width: 300px;
height: 400px;
border: 1px solid green;
/*方法二:使用transform属性*/
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
上述两种方式都能实现div如下的水平、垂直居中: