一个盒子在另一个盒子中垂直居中的方法

今天介绍几种让一个盒子在另一个盒子中居中的方法;

内联元素:给子盒子设置display属性为inline,然后在设置line-height为父盒子的高度

html:

    <div class="box">
        <p>p标签</p>
    </div>
css:

.box {
            width: 200px;
            height: 200px;
            margin: 100px auto;
            border: 1px solid #f00;
            text-align: center;
        }
        p {
            display: inline;
            line-height: 200px;
            background-color: #f40;
        }

结果:

对于内联元素垂直居中的方法还有很多,此处只介绍一种,重点介绍两种块状元素垂直居中的方法。

块状元素:

1、父盒子设置display属性为flex,flex-direction:column, justify-content: center;

html:

	<div class="box">
        	<div class="small"></div>
    	</div>
css:

 .box {
            width: 200px;
            height: 200px;
            margin: 100px auto;
            border: 1px solid #f00;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }
        .small {
            width: 100px;
            height: 100px;
            background-color: #f40;
        }
结果:

2、设置父盒子display属性值为 -webkit-box,;-webkit-box-orient:horizontal;-webkit-box-align:center;

html:

<div class="box">
        <div class="small"></div>
    </div>
css:

 .box {
            width: 200px;
            height: 200px;
            margin: 100px auto;
            border: 1px solid #f00;
            display:-webkit-box;
            -webkit-box-orient:horizontal;
            -webkit-box-align:center;
        }
        .small {
            width: 100px;
            height: 100px;
            background-color: #f40;
        }
结果:


让元素垂直居中的方法还有很多,这里就不一一介绍了。本人水平有限,写的不好的地方欢迎指出,共同讨论。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值