如何用css让一个容器水平垂直居中

方法一:

以前设置里面的绿div总是会使用{position:absolute;left:50%;top:50%;margin-left:-div宽度的一半;margin-top:-div高度的一半}。

这样比较麻烦,还需要自己计算高度和宽度,后来发现可以使用transform:translate(-50%,-50%);来代替margin,就能很好的解决了。

代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
    <style>
    .box{
      width:400px;
      height:400px;
      margin:0 auto;
      position:relative;
      border:1px solid black;
    }
    .content{
      width:200px;
      height:200px;
      background:green;
      position:absolute;
      left:50%;
      top:50%;
      transform:translate(-50%,-50%);
    }
    </style>
  </head>
  <body>
    <div class="box">
      <div class="content"></div>
    </div>
  </body>
</html>

 

方法二:

<div class="box4">
    <div class="child4"></div>
</div>
.box4{
    width:100px;
    height:100px;
    background:gray;
    position:relative;
}
.child4{
    background:red;
    width:50px;
    height:50px;
    margin:auto;
    position:absolute;
    top:0;
    left:0;
    bottom:0;
    right:0;
}

 

方法三:

<div class="box1">
    <div class="child1"></div>
</div>
        .box1{
                width:100px;
                height:100px;
                background:gray;
                text-align:center;/*居中效果只对文本内容和行内元素有效*/
                display:table-cell;
                vertical-align:middle;
            }
            .child1{
                display:inline-block;
                background:red;
                width:50px;
                height:50px;
            }

 

方法四:

<div class="box2">
    <div class="child2"></div>
</div>
.box2{
    width:100px;
    height:100px;
    background:gray;
    display:table-cell;
    vertical-align:middle;
}
.child2{
    margin:0 auto;/*在元素本身上设置,可以实现块级元素水平居中*/
    background:red;
    width:50px;
    height:50px;
}

 方法五:

display:flex + margin:auto

<div class="box2">
    <div class="child2"></div>
</div>
.box2{
    width:100px;
    height:100px;
    background:gray;
    display:flex;
}
.child2{
    margin:auto;
    background:red;
    width:50px;
    height:50px;
}

 

转载于:https://www.cnblogs.com/rachelch/p/7515040.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值