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

时间:2023-03-10 06:00:09
如何用css让一个容器水平垂直居中

方法一:

如何用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: 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>

方法二:

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

<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;
}

方法三:

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

<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;
}

方法四:

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

<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;
}