行内及块级元素在块级元素内实现水平垂直居中

行内及块级元素在块级元素内实现水平垂直居中

1、行内元素

  <div>
        <span>This is a text</span>
  </div>
 div{
            height: 200px;
            width: 200px;
            background-color: lightblue;
     }

在这里插入图片描述

(1)方法一
给div中设置line-height为当前块级元素高度,设置text-align:center,即可实现水平垂直居中;

 div{
            height: 200px;
            width: 200px;
            background-color: lightblue;
            line-height: 200px;
            text-align: center;
    }

效果如下
在这里插入图片描述(2)方法二

利用伸缩盒布局给div设置如下属性:

 div{
            height: 200px;
            width: 200px;
            background-color: lightblue;
            display: flex;
            justify-content: center;
            align-items: center;
        }

效果同上。
2、块级元素

<div id="outer">
        <div id="inner"></div>
</div>
     #outer{
            width: 200px;
            height: 200px;
            background-color:blue;
        }
     #inner{
            width: 100px;
            height: 100px;
            background-color: aquamarine;
        }

在这里插入图片描述

(1)方法一
利用定位布局,给父元素相对定位,子元素绝对定位,left,top,bottom,right都为0,且子元素magin:auto

 #outer{
            width: 200px;
            height: 200px;
            background-color:blue;
            position: relative;
        }
 #inner{
            width: 100px;
            height: 100px;
            background-color: aquamarine;
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            margin: auto;
        }

效果如下:
在这里插入图片描述还可以在父元素设置相对定位,子元素设置绝对定位的基础上,设置子元素向左和向上偏移50%,这时块级子元素位于父元素的右下,那么再向上向左偏移子元素本身宽高的一半即可

 #inner{
             width: 100px;
             height: 100px;
             background-color: peachpuff;
             position: absolute;
             top: 50%;
             left: 50%;
             margin-top:-50px;
             margin-left:-50px ;
         }

(2)方法二
和行内元素一样块级元素也可以使用伸缩盒布局来实现水平垂直居中,只给父元素设置如下属性即可

 #outer{
            width: 200px;
            height: 200px;
            background-color: blue;
            display: flex;
            justify-content: center;
            align-items: center;
        }

还可以在父元素中只设置 display: flex;在子元素中设置 margin: auto;来实现

#outer{
            width: 200px;
            height: 200px;
            background-color: blue;
            display: flex;
        }
        #inner{
            width: 100px;
            height: 100px;
            background-color: aquamarine;
            margin: auto;
        }

效果同上。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值