CSS盒模型实现元素水平垂直居中的方法汇总
最编程
2024-02-13 08:20:10
...
居中总结
居中:盒子在其包含块中居中
行盒(行块盒)水平居中
方法:直接设置行盒(行块盒)父元素text-align:center
//a、span、img、input等行盒元素水平居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
margin: 30px;
height: 100px;
background: skyblue;
text-align: center;
}
.line-block {
display: inline-block;
width: 200px;
height: 50px;
background: green;
}
</style>
</head>
<body>
<div>
<a href="">超链接</a>
</div>
<div>
<span class="line-block"></span>
</div>
</body>
</html>
常规流块盒的水平居中
方法:定宽,设置左右margin为auto,上下没要求。 必须定宽,因为宽度吸收空间的能力比margin强
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.container{
margin: 20px;
height: 300px;
background: skyblue;
}
p {
width: 400px;
height: 200px;
background: red;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="container">
<p></p>
</div>
</body>
</html>
绝对定位元素的水平居中
方法:定宽,设置左右的坐标为0(left:0,right:0),将左右margin设置为auto
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.container{
margin: 20px;
height: 300px;
background: skyblue;
position: relative;
}
p {
width: 400px;
height: 200px;
background: red;
margin: 0 auto;
position: absolute;
left: 0;
right: 0;
}
</style>
</head>
<body>
<div class="container">
<p></p>
</div>
</body>
</html>
实际上,固定定位(fixed)是绝对定位(absolute)的特殊情况
单行文本的垂直居中
方法:设置文本所在元素的行高,为整个区域的高度
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
h1{
height: 100px;
background: skyblue;
/* 垂直居中 */
line-height: 100px;
/* 水平居中 */
text-align: center;
}
</style>
</head>
<body>
<h1>标题</h1>
</body>
</html>
行块盒或块盒内多行文本的垂直居中
方法:没有完美方案,设置盒子上下padding相同,达到类似的效果。缺点是无法知晓盒子的高度。 或者在多行文本外再套一层标签,设置标签高度,使用绝对定位的垂直居中。
绝对定位的垂直居中
方法:定高,设置上下的坐标为0(top:0,bottom:0),将上下margin设置为auto
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.container{
margin: 20px;
background: skyblue;
height: 200px;
position: relative;
}
p{
width: 500px;
height: 100px;
background: red;
position: absolute;
/* left: 0;
right: 0; */
top: 0;
bottom: 0;
margin: auto 0;
}
</style>
</head>
<body>
<div class="container">
<p></p>
</div>
</body>
</html>
下一篇: 盒模型大法好!轻松实现CSS居中样式