<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>元素水平、垂直居中</title>
<style>
body {
margin: 0px 0px;
padding: 20px 20px;
}
/* 公共css */
.demo {
width: 300px;
height: 300px;
border: 1px solid black;
position: relative;
}
.box {
position: absolute;
width: 200px;
height: 200px;
background-color: red;
}
/* demo1 */
.box1 {
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
/* demo2 */
.box2 {
left: calc(50% - 100px);
top: calc(50% - 100px);
}
/* demo3 */
.demo3 {
width: 300px;
height: 300px;
border: 1px solid black;
display: flex;
align-items: center;
justify-content: center;
}
/* demo4 */
.box4 {
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
/* demo5 */
.demo5 {
width: 300px;
height: 300px;
border: 1px solid black;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.box5 {
width: 200px;
height: 200px;
background-color: red;
display: inline-block;
}
</style>
</head>
<body>
<div class="demo">
<div class="box box1">demo1</div>
</div>
<div class="demo">
<div class="box box2">demo2</div>
</div>
<div class="demo3">
<div class="box box3">demo3</div>
</div>
<div class="demo">
<div class="box box4">demo4</div>
</div>
<div class="demo5">
<div class="box5">demo5</div>
</div>
<script></script>
</body>
</html>
元素水平垂直居中的几种方式
最新推荐文章于 2023-01-02 14:59:08 发布