在开发过程中不可避免的就是各种居中,块级、行内级、定高、不定高、垂直、水平还是水平垂直居中。都有哪些实现方案,在开发中应该选用哪个方案比较合适,这里我们就来梳理一下。以便以后使用的时候更加得心应手。
水平居中
行内元素水平居中
1. text-align:center
当我们想要给一个行内元素设置水平居中时,只需要对其父元素设置text-align:center;
,我们可以看一下示例:
<body>
<div class="parent">
<span class="child">1243</span>
</div>
</body>
<style>
.parent {
width: 200px;
height: 200px;
text-align: center;
background-color: aquamarine;
}
</style>
块级元素
定宽块级元素
2. margin-left、margin-right
我们可以通过一个块级元素的margin-left
和margin-right
同时设置为auto
来使其居中。但是这种实现方式是有前提的,就是该元素必须是定宽的,也就是说是设置的有width
属性的。毕竟如果不设置宽度,子元素会撑满父元素,也就不存在居中一说了。我们来看一下简单实现:
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
<style>
.parent {
background-color: bisque;
}
.child {
width: 200px;
height: 200px;
margin: 0 auto;
background-color: brown;
}
</style>
3. margin-left+transform实现
我们可以给子元素设置左边距百分之五十,在设置transform
在水平方向移动负百分之五十,就可以设置子元素基于父元素居中。在这种方案中如果我们不设置子元素宽度,子元素宽度会因为设置百分之五十的左边距,元素宽度自动变为父元素的一半。所以设置宽度不设置宽度都可,根据我们需要,个人认为在需要设置子元素宽度的情况下使用比较合适。我们来看一下简单实现:
<body>
<div class="parent">
<div class="child">我是一个居中子元素</div>
</div>
</body>
<style>
.parent {
width: 500px;
background-color: bisque;
}
.child {
width: 400px;
margin-left: 50%;
transform: translateX(-50%);
background-color: brown