CSS实现垂直水平居中

  • 宽度和高度已知
<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>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容