CSS(层叠样式表)是一种用于描述HTML或XML(包括SVG、MathML等各种XML方言)文档样式的样式表语言。通过CSS,可以控制网页中元素的布局、颜色、字体等样式。
在网页设计中,经常需要将一个div
元素居中对齐,使其在父容器中水平和垂直居中。
div
元素在其父容器中水平居中。div
元素在其父容器中垂直居中。div
元素在其父容器中同时水平和垂直居中。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>水平居中示例</title>
<style>
.container {
text-align: center;
}
.centered-div {
display: inline-block;
width: 200px;
height: 100px;
background-color: lightblue;
}
</style>
</head>
<body>
<div class="container">
<div class="centered-div">水平居中的div</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>垂直居中示例</title>
<style>
.container {
height: 300px;
display: flex;
align-items: center;
}
.centered-div {
width: 200px;
height: 100px;
background-color: lightgreen;
}
</style>
</head>
<body>
<div class="container">
<div class="centered-div">垂直居中的div</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>水平和垂直居中示例</title>
<style>
.container {
height: 300px;
display: flex;
justify-content: center;
align-items: center;
}
.centered-div {
width: 200px;
height: 100px;
background-color: lightcoral;
}
</style>
</head>
<body>
<div class="container">
<div class="centered-div">水平和垂直居中的div</div>
</div>
</body>
</html>
text-align: center;
无法垂直居中?原因:text-align: center;
只能实现水平居中,无法实现垂直居中。
解决方法:使用Flexbox布局或Grid布局来实现垂直居中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>垂直居中示例</title>
<style>
.container {
height: 300px;
display: flex;
align-items: center;
}
.centered-div {
width: 200px;
height: 100px;
background-color: lightgreen;
}
</style>
</head>
<body>
<div class="container">
<div class="centered-div">垂直居中的div</div>
</div>
</body>
</html>
原因:绝对定位需要手动计算偏移量,容易出错。
解决方法:使用Flexbox布局或Grid布局来实现居中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>水平和垂直居中示例</title>
<style>
.container {
height: 300px;
display: flex;
justify-content: center;
align-items: center;
}
.centered-div {
width: 200px;
height: 100px;
background-color: lightcoral;
}
</style>
</head>
<body>
<div class="container">
<div class="centered-div">水平和垂直居中的div</div>
</div>
</body>
</html>
领取专属 10元无门槛券
手把手带您无忧上云