css3讓盒子水平居中的方法:1、使用margin屬性,給盒子元素添加“margin: 0 auto;”樣式即可水平居中;2、利用flex彈性布局來實現(xiàn)水平居中;3、利用position和transform屬性實現(xiàn)水平居中。
本教程操作環(huán)境:windows7系統(tǒng)、CSS3&&HTML5版、Dell G3電腦。
在CSS中如何讓盒子水平居中是很常見的面試題,盒子居中是相對于父元素來說的,因此我們讓盒子居中時,往往采用嵌套的方式,讓父盒子套著子盒子 。
在父子盒子嵌套下,讓子盒子居中的方式:
-
第一種方法:margin: 0 auto,使用邊框,但是margin使用會影響其他盒子的使用,不太推薦使用;
-
第二種方法:position, 使用定位,子絕父相,再left:50%,margin-left:負的盒子寬度的一半,這是最常用的方法;
-
第三種方法:flex,彈性布局,讓子盒子居中,但是樣式要寫在父盒子中,display:flex,just-content:center;
-
第四種方法:在position基礎(chǔ)上,把margin-left換成CSS3中的transform:translate(-50px);
-
第五種方法:在position的基礎(chǔ)上,只保留子絕父相,然后在子盒子中加上margin:auto、left:0、right:0;
補充:在第五種方法上,加上top:0,bottom:0,可以實現(xiàn)垂直和水平都居中
<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實現(xiàn)水平居中:
<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的基礎(chǔ)上,只保留子絕父相,然后在子盒子中加上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>
以上幾種方法都可以實現(xiàn)盒子的水平居中,如果大家有其它優(yōu)(奇)秀(葩)方法,歡迎交流鴨!
第五種方法補充:再加上top:0,bottom:0可以實現(xiàn)水平和垂直都居中 :
<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視頻教程)