文字水平居中
p{
text-align: center;
}
<p>啦啦啦德玛西亚</p>
文字水平垂直居中
设置padding高度自动撑开
div{
text-align: center;
}
<div>啦啦啦德玛西亚</div>
flex
div{
display: flex;
justify-content: center;
align-items: center;
}
<div>啦啦啦德玛西亚</div>
子元素在父元素中水平垂直居中
方法一 position + margin: auto 实现
.red{
width: 100px;
height: 100px;
background-color: red;
}
.blue{
width: 500px;
height: 500px;
background-color: blue;
}
.out{
position: relative;
}
.inner{
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
<div class="out blue">
<div class="inner red">
</div>
</div>
方法二 (子元素已知宽高) position + margin 负值 实现
.red{
width: 100px;
height: 100px;
background-color: red;
}
.blue{
width: 500px;
height: 500px;
background-color: blue;
}
.out{
position: relative;
}
.inner{
position: absolute;
left: 50%;
top: 50%;
margin: -50px 0 0 -50px;
}
<div class="out blue">
<div class="inner red">
</div>
</div>
方法三 (子元素已知宽高) position + transform负值 实现
.red{
width: 100px;
height: 100px;
background-color: red;
}
.blue{
width: 500px;
height: 500px;
background-color: blue;
}
.out{
position: relative;
}
.inner{
position: absolute;
left: 50%;
top: 50%;
transform: translate( -50px ,-50px);
}
<div class="out blue">
<div class="inner red">
</div>
</div>
方法四 flex 实现
.red{
width: 100px;
height: 100px;
background-color: red;
}
.blue{
width: 500px;
height: 500px;
background-color: blue;
}
.out{
display: flex;
justify-content: center;
align-items: center;
}
.inner{
}
<div class="out blue">
<div class="inner red">
</div>
</div>
方法五 模拟table实现 子元素设置margin:auto
<style>
.red{
width: 100px;
height: 100px;
background-color: red;
}
.blue{
width: 500px;
height: 500px;
background-color: blue;
}
.out{
display: table-cell;
vertical-align: middle;
}
.inner{
margin: auto;
}
</style>
<body>
<div class="out blue">
<div class="inner red">
</div>
</div>
</body>
方法六 模拟table实现 子元素设置inline-block
<style>
.red{
width: 100px;
height: 100px;
background-color: red;
}
.blue{
width: 500px;
height: 500px;
background-color: blue;
}
.out{
display: table-cell;
vertical-align: middle;
text-align: center;
}
.inner{
display: inline-block;
}
</style>
<body>
<div class="out blue">
<div class="inner red">
</div>
</div>
</body>