CSS实现垂直居中

垂直居中
1.元素高度确定的单行文本垂直居中
  • 元素设置 line-height,其值与元素高度 height 相同
     <style>
        .background{
            background-color: #368;
            width: 400px;
            height: 200px;
            display: flex;
            align-items: center;
        }
        p{
            line-height: 400px;
            color: #fff;
        }
    </style>
    <div class="background">
        <p>HELLO!</p>
    </div>

     效果图:

     

2.元素高度确定的多行文本、图片、块级元素的垂直居中

     方法一:

  • 父元素设置 position: relative
  • 子元素设置 position: absolute,top: 50%,设置 margin-top 对子元素进行上移,值的大小为子元素高度的一半
  • 缺点:灵活性差,不利于维护,position: absolute 和 position: relative 会带来副作用
    <style>
        .background{
            position: relative;
            background-color: #368;
            width: 500px;
            height: 500px;
        }
        .test{
            position: absolute;
            top: 50%;
            width: 150px;
            height: 150px;
            margin-top: -75px;
            background-color: #eee;
        }
    </style>
    <div class="background">
        <div class="test">
        </div>
    </div>

     效果图:

    

      方法二:

  • 父元素设置 display: flex,align-items: center
  • 父元素要指定宽度和高度
<style>
        .background{
            background-color: #368;
            width: 400px;
            height: 400px;
            display: flex;
            display: -webkit-flex; /*Safari*/
            align-items: center; /*垂直居中,justify-content: center; 可设置水平居中*/
        }
        .test{
            width: 100px;
            height: 100px;
            background-color: #eee;
        }
    </style>
    <div class="background">
        <div class="test">
        </div>
    </div>

     效果图:

     

欢迎补充!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值