在web前端实际项目中,我们通常需要让元素居中:1. 一段文本的水平居中,2. 一张图片的水平居中,3. 一个块级元素的水平居中;4. 单行文本的竖直居中,5. 不确定高度的一段文本竖直居中,6. 确定高度的块级元素竖直居中,7. 居中其他方法。
<!DOCTYPE html>
<html>
<head>
<title>文字水平居中</title>
<meta charset="utf-8">
<style>
.text-center {
width: 200px;
height: 100px;
text-align: center;
background-color: #f54;
}
</style>
</head>
<body>
<div class="text-center">水平居中</div>
</body>
</html>
2 . 让图片水平居中,让父元素使用 text-align: center; (edge,firefix,chrome,opera,ie测试通过):
<!DOCTYPE html>
<html>
<head>
<title>图片水平居中</title>
<meta charset="utf-8">
<style>
.text-center {
width: 300px;
height: 150px;
text-align: center;
background-color: #f54;
}
</style>
</head>
<body>
<div class="text-center">
<img src="baidu.jpg" alt="baidu">
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>块级元素居中</title>
<meta charset="utf-8">
<style>
.parent-box {
width: 250px;
height: 150px;
background-color: #f98;
}
.child-box {
width: 200px;
height: 100px;
background-color: #f00;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<div class="parent-box">
<div class="child-box">块级元素水平居中</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>单行文本竖直居中</title>
<meta charset="utf-8">
<style>
.line-height {
width: 250px;
height: 100px;
line-height: 100px;
background-color: #f00;
}
</style>
</head>
<div class="line-height">单行文本竖直居中</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>不确定高度的一段文本竖直居中</title>
<meta charset="utf-8">
<style>
.padding {
width: 150px;
background-color: #f00;
padding-top: 30px;
padding-bottom: 30px;
}
</style>
</head>
<div class="padding">不确定高度的一段文本竖直居中</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>确定高度的块级元素竖直居中</title>
<meta charset="utf-8">
<style>
.parent-box {
position: relative;
width: 250px;
height: 150px;
background-color: #f00;
}
.child-box {
position: absolute;
top: 50%;
width: 200px;
height: 100px;
margin-top: -50px;
background-color: #f54;
}
</style>
</head>
<div class="parent-box">
<div class="child-box">确定高度的块级元素竖直居中</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>verticalmiddle</title>
<meta charset="utf-8">
<style>
.parent-box{
width: 200px;
height: 200px;
background-color: #f00;
}
.child-box{
position: relative;
top: 50%;
width: 100px;
height: 100px;
background-color: #0f0;
-webkit-transform: translateY(-50%);
-o-transform: translateY(-50%);
transform: translateY(-50%);
}
</style>
</head>
<body>
<div class="parent-box">
<div class="child-box"></div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>居中其他方法</title>
<meta charset="utf-8">
<style>
.parent-box {
position: relative;
width: 250px;
height: 150px;
background-color: #f00;
}
.child-box {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 200px;
height: 100px;
margin: auto;
background-color: #f54;
}
</style>
</head>
<div class="parent-box">
<div class="child-box">居中其他方法</div>
</div>
</body>
</html>
2025 - 快车库 - 我的知识库 重庆启连科技有限公司 渝ICP备16002641号-10
企客连连 表单助手 企服开发 榜单123