首頁  >  文章  >  web前端  >  css3如何讓盒子水平居中

css3如何讓盒子水平居中

青灯夜游
青灯夜游原創
2022-01-20 18:32:1016399瀏覽

css3讓盒子水平居中的方法:1、使用margin屬性,為盒子元素添加「margin: 0 auto;」樣式即可水平居中;2、利用flex彈性佈局來實現水平居中;3、利用position和transform屬性實作水平居中。

css3如何讓盒子水平居中

本教學操作環境:windows7系統、CSS3&&HTML5版、Dell G3電腦。

在CSS中如何讓盒子水平居中是很常見的面試題,盒子居中是相對於父元素來說的,因此我們讓盒子居中時,往往採用嵌套的方式,讓父盒子套著子盒子。

 在父子盒子嵌套下,讓子盒子居中的方式:

  • 第一種方法:margin: 0 auto,使用邊框,但是margin使用會影響其他盒子的使用,不太建議使用;

  • 第二種方法:position, 使用定位,子絕父相,再left:50%,margin-left:負的盒子寬度的一半,這是最常用的方法;

  • 第三種方法:flex,彈性佈局,讓子盒子居中,但是樣式要寫在父盒子中,display:flex,just-content:center;

  • 第四種方法:在position基礎上,把margin-left換成CSS3中的transform:translate(-50px );

  • 第五種方法:在position的基礎上,只保留子絕父相,然後在子盒子中加上margin:auto、left:0、right:0 ;

    補充:在第五種方法上,加上top:0,bottom:0,可以實現垂直和水平都居中

<div id="father">
    <div id="son"></div>
</div>
<style>
    #father{
        width: 400px;
        height: 200px;
        border: 3px solid pink;
    }
    #son{
        width: 100px;
        height: 100px;
        border: 2px solid red;
    }
</style>

使用margin實現水平居中:

<style>
#father{
    width: 400px;
    height: 200px;
    border: 3px solid pink;
    margin: 30px auto; /* 让父元素相对于body居中 */
}
#son{
    width: 100px;
    height: 100px;
    border: 2px solid red;
    margin: 0 auto;/* 让子元素相对于father居中 */
}
</style>

 使用定位,子絕父相,再left:50%,margin-left:負的盒子寬度的一半:

<style>
#father{
    width: 400px;
    height: 200px;
    border: 3px solid pink;
    margin: 0 auto;
    position: relative;
}
#son{
    width: 100px;
    height: 100px;
    border: 2px solid red;
    position: absolute;
    left: 50%;
    margin-left: -50px;
}
</style>

flex,彈性佈局,讓子盒子居中,但是樣式要寫在父盒子中:

<style>
#father{
    width: 400px;
    height: 200px;
    border: 3px solid pink;
    margin: 0 auto;
    display: flex;
    justify-content: center;
}
#son{
    width: 100px;
    height: 100px;
    border: 2px solid red;
}
</style>

在position的基礎上,只保留子絕父相,然後在子盒子中加上margin:auto、left:0、right:0:

<style>
#father{
    width: 400px;
    height: 200px;
    border: 3px solid pink;
    margin: 0 auto;
    position: relative;
}
#son{
    width: 100px;
    height: 100px;
    border: 2px solid red;
    position: absolute;
    margin: auto;
    left: 0;
    right: 0;
}
</style>

以上幾種方法都可以實現盒子的水平居中,如果大家有其它優(奇)秀(葩)方法,歡迎交流鴨!

 第五種方法補充:再加上top:0,bottom:0可以實現水平和垂直都居中:

<style>
#father{
    width: 400px;
    height: 200px;
    border: 3px solid pink;
    margin: 0 auto;
    position: relative;
}
#son{
    width: 100px;
    height: 100px;
    border: 2px solid red;
    position: absolute;
    margin: auto;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
}
</style>

(學習影片分享:css影片教學

以上是css3如何讓盒子水平居中的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn