1.用inline-block和vertical-align來(lái)實(shí)現(xiàn)居中:這種方法適合于未知寬度高度的情況下。
<div id="container"> <div id="center-div"> xxx </div></div>...#container{ **text-align: center**; height: 400px; background: #4dc71f;}#container:before{ content: ""; height: 100%; **display: inline-block; vertical-align: middle;** margin-right: -0.25em;}#center-div{ display: inline-block; vertical-align: middle; background: #2aabd2;}參考:https://CSS-tricks.com/centering-in-the-unknown/
2.用相對(duì)絕對(duì)定位和負(fù)邊距實(shí)現(xiàn)上下左右居中:高度和寬度已知
<div class="div2"> <img class="img2" src="images/hongbao.png"></div>....div2{ height: 600px; width: 600px; position: relative; border: 2px solid #000;}.img2{ height: 200px; width: 200px; position: relative; **top: 50%; left: 50%; margin: -100px 0 0 -100px;**}首先相對(duì)父元素top,left定位在50%的位置,這時(shí)候只是圖片左上角居中,而中心點(diǎn)還沒居中,加上margin: -100px 0 0 -100px;利用負(fù)邊距把圖片的中心點(diǎn)位于父元素的中心點(diǎn),從而實(shí)現(xiàn)垂直水平居中
3.利用絕對(duì)定位來(lái)實(shí)現(xiàn)居中:適合高度,寬度已知的情況。
<div id="container"> <div id="center-div"> xxx </div></div>...#container{ text-align: center; height: 400px; background: #4dc71f; position: relative;}#center-div{ position: absolute; margin: auto; top: 0; right: 0; left:0; bottom: 0; width: 200px; height: 200px; background: #2b669a;}4.使用table-cell,inline-block實(shí)現(xiàn)水平垂直居中:適合高度寬度未知的情況
#container{ display: table-cell; text-align: center; vertical-align: middle; height: 300px; background: #ccc;}#center-div{ display: inline-block;}5.使用css3中的transform來(lái)時(shí)實(shí)現(xiàn)水平垂直居中:適合高度寬度未知的情況
#container{ position: relative; height: 200px; background: #333;}#center-div{ position: absolute; top:50%; left: 50%; transform: translate(-50%,-50%);}還可以使用Flexbox來(lái)實(shí)現(xiàn)水平垂直居中;適合寬度高度未知情況,但是要注意兼容性
<div id="p_2"> <div id="c_2"> xxxxxxx </div></div>#p_2{ display: flex; justify-content: center; align-items: center; width: 200px; height: 200px; background: #009f95;}新聞熱點(diǎn)
疑難解答
圖片精選