CSS(层叠样式表)是一种用于描述HTML或XML(包括SVG、MathML等各种XML方言)文档样式的样式表语言。居中是CSS中一个常见的布局需求,可以通过多种方式实现。
text-align: center;
对文本进行水平居中。margin: 0 auto;
对块级元素进行水平居中。display: flex; justify-content: center;
。display: grid; justify-items: center;
。transform
属性:position: absolute; top: 50%; transform: translateY(-50%);
。display: flex; align-items: center;
。display: grid; align-items: center;
。display: flex; justify-content: center; align-items: center;
。display: grid; place-items: center;
。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Horizontal Centering</title>
<style>
.container {
text-align: center;
}
.box {
display: inline-block;
width: 200px;
height: 100px;
background-color: lightblue;
}
</style>
</head>
<body>
<div class="container">
<div class="box">Centered Box</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>Vertical Centering</title>
<style>
.container {
position: relative;
height: 300px;
}
.box {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 200px;
height: 100px;
background-color: lightgreen;
}
</style>
</head>
<body>
<div class="container">
<div class="box">Centered Box</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>Horizontal and Vertical Centering</title>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 300px;
}
.box {
width: 200px;
height: 100px;
background-color: lightcoral;
}
</style>
</head>
<body>
<div class="container">
<div class="box">Centered Box</div>
</div>
</body>
</html>
margin: 0 auto;
无法居中?原因:
解决方法: 确保元素是块级元素,并且设置了明确的宽度。
.box {
display: block;
width: 200px;
margin: 0 auto;
}
原因:
display: flex;
。justify-content
和align-items
属性。解决方法:
确保父容器设置了display: flex;
,并且正确设置了justify-content
和align-items
属性。
.container {
display: flex;
justify-content: center;
align-items: center;
height: 300px;
}
通过以上方法,可以有效地在谷歌浏览器中实现CSS居中效果。
领取专属 10元无门槛券
手把手带您无忧上云