css 如何使一个盒子水平垂直居中
方法一、使用 flex 布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style>
.father {
width: 500px;
height: 500px;
background-color: brown;
+ display: flex;
+ justify-content: center;
+ align-items: center;
}
.son {
width: 100px;
height: 100px;
background-color: cadetblue;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
方法二、使用定位和 transform
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style>
.father {
width: 500px;
height: 500px;
background-color: chocolate;
position: relative;
}
.son {
width: 100px;
height: 100px;
background-color: darkcyan;
position: absolute;
left: 50%;
top: 50%;
+ transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
方法三、使用定位和 magin
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style>
.father {
width: 500px;
height: 500px;
background-color: chocolate;
position: relative;
}
.son {
width: 100px;
height: 100px;
background-color: darkcyan;
position: absolute;
left: 50%;
top: 50%;
+ margin-top: -50px;
+ margin-left: -50px;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
方法四、使用 display:table-cell
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style>
.father {
width: 500px;
height: 500px;
background-color: chocolate;
+ display: table-cell;
+ vertical-align: middle;
}
.son {
width: 100px;
height: 100px;
background-color: darkcyan;
+ margin: auto;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
本文介绍了使用CSS将一个盒子水平垂直居中的四种常见方法:1) 使用Flex布局;2) 利用定位和transform属性;3) 通过定位和margin负值;4) 使用display:table-cell。详细代码示例帮助理解每种方法的实现细节。
1168

被折叠的 条评论
为什么被折叠?



