前言
元素居中是常见的css布局,个人较懒,总是用到了搜一下,但觉得自己做的不对,需要系统的总结一下,于是参照网上大神们的文章,写了一篇总结。
元素居中方法
1. 利用绝对定位和相对定位 (元素居中)
html
```
<div class="container">
<div class="content">我是测试内容</div>
</div>
```
css
```
.box {
width: 300px;
height: 300px;
background: #ddd;
position: relative;
}
.child {
width: 150px; /* 可有可无 */
height: 100px;
line-height: 100px;
background: #F7A750;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
/*translate比margin要好,这时不需要居中元素有已知的宽高
注意:margin使用百分比时,是基于父元素的尺寸*/
}
// 除使用translate外,还可以用margin: auto
.child {
width: 150px; /* 该方法,必须指明宽高 */
height: 100px;
line-height: 100px;
background: #F7A750;
position: absolute;
top: 0; /* top/bottom , left/right必须成对存在时,才生效 */
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
```
效果
2. 设置占位元素 (元素居中)
html
```
<div class="box">
<div class="base"></div>
<div class="child">使用了占位元素</div>
</div>
```
css
```
.box {
width: 300px;
height: 300px;
background: #ddd;
}
.base {
height: 50%;
background: #F7A750;
}
.child {
height: 100px;
background: rgba(255, 255, 255, 0.6);
line-height: 100px;
margin-top: -50px;
}
```
效果
3. 使用flex布局 (元素居中)
html
```
<div class="container">
<div class="content">我是测试内容</div>
</div>
```
css
```
.box {
width: 300px;
height: 300px;
background: #ddd;
display: flex;
align-items: center;
}
.child {
width: 300px;
height: 100px;
background: #F7A750;
line-height: 100px;
}
```
效果
4. 通过padding&margin实现伪居中 (元素居中, 内容居中)
父组件不指定高度(但要指定宽度,不然宽度会为100%),而指定其padding,实现子元素的居中
html
```
<div class="container">
<div class="content">我是测试内容</div>
</div>
```
css
```
#box {
width: 300px;
background: #ddd;
padding: 100px 0;
}
#child {
width: 200px;
height: 100px;
background: #F7A750;
margin: auto;
line-height: 50px;
}
```
效果
内容居中方法
1. flex布局
2. vertical-align: middle;
该样式是控制图片居中
但也可以控制文本居中
html
```
<div class="container">
vertical-align实现文本竖直居中
</div>
```
css
```
.container {
width: 300px;
height: 300px;
background: #ddd;
display: table-cell;
vertical-align: middle;
}
```
效果