手机
当前位置:查字典教程网 >网页设计 > Div+Css教程 >css中常用的几种居中方法(推荐)
css中常用的几种居中方法(推荐)
摘要:在前端面试中,大都会问你div居中的方法:文笔不好,就随便寥寥几句话概括了,不过以后文笔肯定会变得更好一些的。今天我们就细数一下几种方法:1...

在前端面试中,大都会问你div居中的方法:

文笔不好,就随便寥寥几句话概括了,

不过以后文笔肯定会变得更好一些的。

今天我们就细数一下几种方法:

1,使用position:absolute,设置left、top、margin-left、margin-top的属性

CSS Code复制内容到剪贴板 .one{ position:absolute; width:200px; height:200px; top:50%; left:50%; margin-top:-100px; margin-left:-100px; background:red; }

这种方法基本浏览器都能够兼容,不足之处就是需要固定宽高。

2,使用position:fixed,同样设置left、top、margin-left、margin-top的属性

CSS Code复制内容到剪贴板 .two{ position:fixed; width:180px; height:180px; top:50%; left:50%; margin-top:-90px; margin-left:-90px; background:orange; }

大家都知道的position:fixed,IE是不支持这个属性的

3,利用position:fixed属性,margin:auto这个必须不要忘记了。

CSS Code复制内容到剪贴板 .three{ position:fixed; width:160px; height:160px; top:0; rightright:0; bottombottom:0; left:0; margin:auto; background:pink; }

4,利用position:absolute属性,设置top/bottom/right/left

CSS Code复制内容到剪贴板 .four{ position:absolute; width:140px; height:140px; top:0; rightright:0; bottombottom:0; left:0; margin:auto; background:black; }

5,利用display:table-cell属性使内容垂直居中

CSS Code复制内容到剪贴板 .five{ display:table-cell; vertical-align:middle; text-align:center; width:120px; height:120px; background:purple; }

6,最简单的一种使行内元素居中的方法,使用line-height属性

CSS Code复制内容到剪贴板 .six{ width:100px; height:100px; line-height:100px; text-align:center; background:gray; }

这种方法也很实用,比如使文字垂直居中对齐

7,使用css3的display:-webkit-box属性,再设置-webkit-box-pack:center/-webkit-box-align:center

CSS Code复制内容到剪贴板 .seven{ width:90px; height:90px; display:-webkit-box; -webkit-box-pack:center; -webkit-box-align:center; background:yellow; color:black; }

8,使用css3的新属性transform:translate(x,y)属性

CSS Code复制内容到剪贴板 .eight{ position:absolute; width:80px; height:80px; top:50%; left:50%; transform:translate(-50%,-50%); -webkit-transform:translate(-50%,-50%); -moz-transform:translate(-50%,-50%); -ms-transform:translate(-50%,-50%); background:green; }

这个方法可以不需要设定固定的宽高,在移动端用的会比较多,在移动端css3兼容的比较好

9、最高大上的一种,使用:before元素

CSS Code复制内容到剪贴板 .nine{ position:fixed; display:block; top:0; rightright:0; bottombottom:0; left:0; text-align:center; background:rgba(0,0,0,.5); } .nine:before{ content:''; display:inline-block; vertical-align:middle; height:100%; } .nine.content{ display:inline-block; vertical-align:middle; width:60px; height:60px; line-height:60px; color:red; background:yellow; }

这种方法在我的前面一片文章有详细的介绍:弹窗居中的简单实现方法

以上这篇css中常用的几种居中方法(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持查字典教程网。

【css中常用的几种居中方法(推荐)】相关文章:

CSS中常用的缩写方式

控制DIV中文字绝对居中的简单方法

css中的框架模

div+css垂直居中的五种实现方法

CSS代码中进行注释的三种方法

CSS垂直居中和水平居中方法总结

添加css样式的三种方法

任意图片实现垂直居中的三种方法(兼容性还不错)

css实现body背景图片水平垂直居中方法

IE6下图片下方有空间距的多种解决方法

精品推荐
分类导航