首页 > 开发 > CSS > 正文

css中常用的几种居中方法(推荐)

2024-07-11 08:32:55
字体:
来源:转载
供稿:网友

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

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

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

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

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

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

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

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

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

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

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

CSS Code复制内容到剪贴板
  1. .three{                position:fixed;   
  2.             width:160px;                height:160px;   
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表