目录
水平居中
inline元素:
text-align: center;
<style>
.wrapper {
width: 200px;
height: 200px;
background-color: blue;
/*text-align: center;*/
}
.box {
background-color: aqua;
}
</style>
<body>
<div class="wrapper">
<span class="box">inline元素</span>
</div>
</body>
block元素:
margin: 0 auto;
<style>
.wrapper {
width: 200px;
height: 200px;
background-color: blue;
}
.box {
width: 100px;
/* margin: 0 auto; */
background-color: aqua;
}
</style>
<body>
<div class="wrapper">
<div class="box">block元素</div>
</div>
</body>
position元素:
left: 50%; margin-left: -50px;或 left: 50%; transform: translateX(-50%);有兼容性问题
<style>
.wrapper {
position: relative;
width: 200px;
height: 200px;
background-color: blue;
}
.box {
position: absolute;
width: 100px;
left: 50%; //父元素的一半
margin-left: -50px;//自身的一半
background-color: aqua;
}
</style>
<body>
<div class="wrapper">
<div class="box">position元素</div>
</div>
</body>
垂直居中
inline元素:
父元素加line-height值=height
<style>
.wrapper {
width: 200px;
height: 200px;
background-color: blue;
line-height: 200px;
}
.box {
background-color: aqua;
}
</style>
<body>
<div class="wrapper">
<span class="box">inline元素</span>
</div>
</body>
position元素:
- top: 50%; margin-top: -50px;
- top: 50%; transform: translateY(-50%);有兼容性问题
- top:0; bottom:0; margin:auto 0;
<style>
.wrapper {
position: relative;
width: 200px;
height: 200px;
background-color: blue;
}
.box {
position: absolute;
width: 100px;
height: 100px; // 注意要加个高度
top: 0;
bottom: 0;
margin: auto 0;
background-color: aqua;
}
</style>
<body>
<div class="wrapper">
<div class="box">position元素</div>
</div>
</body>