1. 程式人生 > >css實現水平垂直居中方法總結

css實現水平垂直居中方法總結

form 位置 absolute div 技術 .com 完成 flex image

方法一:使用position 元素已知寬度

<div class="box">
    <div class="content"></div>
</div>
<style>
    .box{width:400px; height: 400px;background:red;position: relative;}
    .content{width:150px;height: 100px;background:green; position: absolute;top:200px;left: 200px;margin-left:-75px;margin-top
: -50px;} </style>

技術分享圖片

方法二:position tranform 元素寬度未知

<div class="box">
    <div class="content"></div>
</div>
<style>
    .box{width:400px; height: 400px;background:red;position: relative;}
    .content{width:150px;height: 100px;background:green; position: absolute;top:200px;left
: 200px;transform: translate(-50%,-50%);} </style>

得到的效果和上圖一樣

當使用這種方法將文字放在div水平垂直的位置的時候,會出現字體邊緣模糊的結果,解決方法是:使用flex完成垂直居中,設置排列方向為column,並設置justify-content: center,最後用text-align: center完成水平居中。方能保證文字顯示清晰。

方法三:felx布局

<style>
    .box{width:400px; height: 400px;background:red;display: flex;justify-content
: center;align-items: center;} .content{width:150px;height: 100px;background:green;} </style> <div class="box"> <div class="content"></div> </div>

效果和上圖一樣

方法四:table-cell布局

因為table-cell相當與表格的td,td為行內元素,無法設置寬和高,所以嵌套一層,嵌套一層必須設置display: inline-block;td的背景覆蓋了紅色,不推薦使用

<style>
    .box{width:400px; height: 400px;background:red;display: table;}
    .content{background:blue;display: table-cell;vertical-align: middle;text-align:center;}
    .inner{background:green;display: inline-block;width: 150px;height: 100px;}
</style>
<div class="box">
    <div class="content">
    <div class="inner"></div>
    </div>
</div>

技術分享圖片

css實現水平垂直居中方法總結