css竖直居中实现

前言

元素居中是常见的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;
}
```

效果

效果图


温故知新

CSS弹性盒子

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值