CSS实现垂直水平居中
2019-08-05 本文已影响0人
尤格萨隆
- 宽度和高度已知
<style>
#box {
width: 400px;
height: 200px;
position: relative;
background: red;
}
#box1{
width: 200px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -50px;
background: green;
}
</style>
<body>
<div id="box">
<div id="box1">
</div>
</div>
</body>
- 宽度和高度未知
<style>
#box{
width: 800px;
height: 400px;
position: relative;
background: red;
}
#box1{
width: 100px;
height: 50px;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
background: green;
}
</style>
<body>
<div id="box">
<div id="box1">
</div>
</div>
</body>
- flex布局
<style>
#box{
width: 400px;
height: 200px;
background: #f99;
display: flex;
justify-content: center; /*实现水平居中*/
align-items: center; /*实现垂直居中*/
}
#box1{
width: 200px;
height: 100px;
background: green;
}
</style>
<body>
<div id="box">
<div id="box1">
</div>
</div>
</body>
- 平移 定位+transform
<style>
#box{
width: 400px;
height: 200px;
background: red;
position: relative;
}
#box1{
width: 200px;
height: 100px;
background: #9ff;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
<body>
<div id="box">
<div id="box1">
</div>
</div>
</body>
- table-cell 布局
<style>
#box{
display: table-cell;
vertical-align: middle
}
#box1{
margin: 0 auto;
}
</style>
<body>
<div id="box">
<div id="box1">
</div>
</div>
</body>