居中总结
居中:盒子在其包含块中居中
行盒(行块盒)水平居中
直接设置行盒(行块盒)父元素text-align:center
<style>
div {
margin: 30px;
background: lightblue;
height: 100px;
text-align: center;
}
.inline-block{
display: inline-block;
width: 300px;
height: 50px;
background: red;
}
img{
height: 50px;
}
</style>
<body>
<div>
<a href="">超链接</a>
</div>
<div>
<span class="inline-block"></span>
</div>
<div>
<img src="1.jpg" alt="">
</div>
<div>
<input type="text">
</div>
</body>
常规流块盒水平居中
定宽,设置左右margin为auto
<style>
.container{
margin: 30px;
height: 200px;
background: lightblue;
}
p{
width: 500px;
height: 100px;
background: red;
margin: 0 auto;
}
</style>
<body>
<div class="container">
<p></p>
</div>
</body>
绝对定位元素的水平居中
定宽,设置左右的坐标为0(left:0, right:0),将左右margin设置为auto
实际上,固定定位(fixed)是绝对定位(absolute)的特殊情况
<style>
.container{
margin: 30px;
height: 200px;
background: lightblue;
position: relative;
}
p{
width: 500px;
height: 100px;
background: red;
margin: 0 auto;
position: absolute;
left: 0;
right: 0;
margin: 0 auto;
}
</style>
<body>
<div class="container">
<p></p>
</div>
</body>
定位元素水平垂直居中
<style>
.container{
margin: 30px;
height: 200px;
background: lightblue;
position: relative;
}
p{
width: 500px;
height: 100px;
background: red;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto auto;
}
</style>
单行文本的垂直居中
设置文本所在元素的行高,为整个区域的高度
h1{
height: 200px;
background: lightblue;
text-align: center;
line-height: 200px;
}
行块盒或块盒内多行文本的垂直居中
没有完美方案
设置盒子上下内边距相同,达到类似的效果。
<style>
div{
background: lightblue;
/* display: inline-block; */
padding: 100px 0;
}
</style>
<body>
<div>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Repudiandae cupiditate distinctio suscipit nihil sed incidunt, provident, laboriosam rem ad repellat excepturi officiis sapiente enim fuga similique quas, vero dolores quae!
</div>
</body>
绝对定位的垂直居中
定高,设置上下的坐标为0(top:0, bottom:0),将上下margin设置为auto
<style>
.container{
margin: 30px;
height: 200px;
background: lightblue;
position: relative;
}
p{
width: 500px;
height: 100px;
background: red;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto auto;
}
</style>