如何将一个子元素水平垂直居中

问: 如何将一个子元素水平垂直居中

  • 方法一:定位 + margin

  父元素相对定位,子元素绝对定位,并设置子元素margin:auto

<style>
    .father{
        position: relative;
        width: 400px;
        height:400px;
    }
    .son{
        position: absolute;
        width: 100px;
        height:100px;
        margin:auto;
    }
    
</style>
<body>
<div class="father">
    <div class="son"></div>
</div>
<body>
  • 方法二:定位 + transform

子元素使用css3中的transform中的translate平移,各偏移负的50%

<style>
    .father{
        position: relative;
        backgroud-color: blue;
        width: 400px;
        height:400px;
    }
    .son{
        width: 100px;
        height:100px;
        backgroud-color: red;
        transform:translate( -50%, -50%)
    }
    
</style>
<body>
<div class="father">
    <div class="son"></div>
</div>
<body>    
  • 方法三:flex布局

 

   新版本flex,父元素上采用flex布局,设置水平方向居中justify-content: center; 垂直方向居中align-items: center;

 

 

<style>
    .father{
        backgroud-color: blue;
        width: 400px;
        height:400px;
        display:flex;
        justify-content: center;
        align-items: center;
    }
    .son{
        width: 100px;
        height:100px;
        backgroud-color: red;
    }
    
</style>
<body>
<div class="father">
    <div class="son"></div>
</div>
<body> 
老版本flex

 

<style>
    .father{
        backgroud-color: blue;
        width: 400px;
        height:400px;
        display: -webkit-box;
        -webkit-box-pack: center;
        -webkit-box-align: center;
    }
    .son{
        width: 100px;
        height:100px;
        backgroud-color: red;
    }
    
</style>
<body>
<div class="father">
    <div class="son"></div>
</div>
<body> 

 

posted @ 2023-03-02 16:33  汤姆猫Tom  阅读(104)  评论(0)    收藏  举报