tft每日頭條

 > 生活

 > css是怎麼實現水平居中的

css是怎麼實現水平居中的

生活 更新时间:2024-05-10 07:30:53

我們在使用css來布局時經常需要進行居中,有時一個屬性就能搞定,有時則需要一定的技巧才能兼容到所有浏覽器,利用css來實現對象的垂直居中有許多不同的方法,比較難的是應該選擇哪種正确的方法。比如我們都知道 margin:0 auto;的樣式能讓元素水平居中,而margin: auto;卻不能做到垂直居中……下面就css居中的一些常用方法做個集中的介紹。

首先是水平居中,最簡單的辦法當然就是:

margin:0 auto;

文字的水平居中方法:

利用line-height設為height的一樣即可:

eg:

.div {

width:200px;

height: 200px;

line-height: 200px;/*實現垂直居中的關鍵*/

text-align:center;

font-size: 36px;

background-color: #ccc;

}

絕對定位居中

父容器元素:position: relative,子元素:position:absolute;

eg:

<div class="box">

<div class="content"></div>

</div>

<style>

.box{position:relative;width:200px;height:200px;background:#999;}

.content{

width: 50%;

height: 50%;

overflow: auto;

margin: auto;

position: absolute;

top: 0; left: 0; bottom: 0; right: 0;

background:#C9F;}

</style>

效果如下所示:

css是怎麼實現水平居中的(學會這幾種方法)1

!注意:高度必須定義,建議加 overflow: auto,防止内容溢出。

flex居中

介紹一下CSS3中的display:flex來實現的水平垂直居中的方法。

eg:

<div class="parent">

<div class="children">我是通過flex的水平垂直居中噢!</div>

</div>

<style>

.parent {

display:flex;

align-items: center;/*垂直居中*/

justify-content: center;/*水平居中*/

width:200px;

height:200px;

background-color:green;

}

.children {

background-color:blue;

color:#FFF;

}

</style>

效果如下所示:

css是怎麼實現水平居中的(學會這幾種方法)2

這種方式最為簡便,就是兼容性不好,不過随着時間的前進,各大浏覽器一定會都兼容的。

css是怎麼實現水平居中的(學會這幾種方法)3

,

更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!

查看全部

相关生活资讯推荐

热门生活资讯推荐

网友关注

Copyright 2023-2024 - www.tftnews.com All Rights Reserved