国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 網站 > WEB開發 > 正文

【css】實現垂直水平居中的幾種方法

2024-04-27 15:15:37
字體:
來源:轉載
供稿:網友

1.用inline-block和vertical-align來實現居中:這種方法適合于未知寬度高度的情況下。

<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.用相對絕對定位和負邊距實現上下左右居中:高度和寬度已知

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

首先相對父元素top,left定位在50%的位置,這時候只是圖片左上角居中,而中心點還沒居中,加上margin: -100px 0 0 -100px;利用負邊距把圖片的中心點位于父元素的中心點,從而實現垂直水平居中

3.利用絕對定位來實現居中:適合高度,寬度已知的情況。

<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實現水平垂直居中:適合高度寬度未知的情況

#container{ display: table-cell; text-align: center; vertical-align: middle; height: 300px; background: #ccc;}#center-div{ display: inline-block;}

5.使用css3中的transform來時實現水平垂直居中:適合高度寬度未知的情況

#container{ position: relative; height: 200px; background: #333;}#center-div{ position: absolute; top:50%; left: 50%; transform: translate(-50%,-50%);}

還可以使用Flexbox來實現水平垂直居中;適合寬度高度未知情況,但是要注意兼容性

<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;}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 万宁市| 出国| 太仓市| 金阳县| 稻城县| 洞口县| 浦江县| 永州市| 玉田县| 平陆县| 亚东县| 双鸭山市| 穆棱市| 江永县| 建湖县| 东乡族自治县| 彰武县| 惠安县| 岳池县| 塔城市| 格尔木市| 昭觉县| 平遥县| 扶沟县| 莎车县| 玛纳斯县| 九江县| 百色市| 安岳县| 华宁县| 土默特右旗| 西乡县| 南京市| 商丘市| 中卫市| 灌云县| 绵阳市| 遵化市| 昌黎县| 广州市| 吉隆县|