1. 程式人生 > 其它 >CSS常用的幾種水平居中的方式

CSS常用的幾種水平居中的方式

技術標籤:CSS和htmlcsscss3htmlhtml5

CSS常用的幾種水平居中的方式

html佈局最常見的就是水平居中對齊,文字在div裡面居中,div在div裡面居中,圖片在div裡面居中等等,今天給大家總結幾個CSS中最常見的幾種水平居中的方式,絕對好用!

文字在div裡面水平居中

html部分

<!DOCTYPE html>
<html>

<head lang="zh">
    <meta http-equiv="X-UA-Compatible" content="IE=edge"
>
<meta charset="utf-8" /> <title>裝置管理</title> <link rel="stylesheet" href="./css/index.css" /> </head> <body> <div class="content"> <div class="box">我是div裡面的文字</div> </
div
>
</body> </html>

CSS部分-利用text-align:center屬性

.box{
        background: yellow;
        width: 200px;
        height: 100px;
        line-height: 100px;/*讓黃色div中的文字內容垂直居中*/
        text-align: center;/*讓文字水平居中*/
        position: absolute;    
    }

實現的效果如下圖文字在在這裡插入圖片描述

div在div裡面水平居中

1.通過屬性margin:0 auto;需注意要設定內層div的寬度。

2.通過flex佈局實現:在外層div上設定:

display:flex;
justify-context:center;/*讓div在div裡面水平居中,該方法在塊級元素和行內元素的水平居中效果上都適用*/
align-items:center;/*讓div在div裡面垂直居中,該方法同樣適用於行內元素的垂直居中*/

圖片在div裡面水平居中

水平居中 在圖片的父元素中用text-algin:center;進行水平居中
html部分

 <div class="wrap">
	    <img src="../assets/img/manage/notice.png" alt="">
       </div>

CSS部分

.wrap{ width: 600px;
       height: 400px; 
       border: 1px #000 solid; 
       text-algin:center
      }

上面介紹了幾種最常見,最簡單的方式,希望對大家有所幫助!