首页 > 开发 > CSS > 正文

css让容器水平垂直居中的7种方式

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

这种css布局平时用的比较多,也是面试题常出的一个题,网上一搜一大丢,不过还是想自己总结一下。
这种方法比较多,本文只总结其中的几种,以便加深印象。
效果图都为这个:

方法一:position加margin

XML/HTML Code复制内容到剪贴板

<div class="wrap">  
    <div class="center"></div>  
</div>  
  

CSS Code复制内容到剪贴板

/**css**/ .wrap { width: 200px; height: 200px; background: yellow; position: relative;   
} .wrap .center { width: 100px; height: 100px; background: green; margin: auto; position: absolute; left: 0; rightright: 0; top: 0; bottombottom: 0;   
}  

兼容性:主流浏览器均支持,IE6不支持

方法二:diaplay:table-cell

XML/HTML Code复制内容到剪贴板

<!– html –>  
<div class="wrap">  
     <div class="center"></div>  
</div>  
  

CSS Code复制内容到剪贴板

/*css*/ .wrap{ width: 200px; height: 200px; background: yellow; display: table-cell; vertical-align: middle; text-align: center;   
} .center{ display: inline-block; vertical-align: middle; width: 100px; height: 100px; background: green;   
}   
  

兼容性:由于display:table-cell的原因,IE67不兼容

方法三:position加 transform

XML/HTML Code复制内容到剪贴板

<!– html –>  
<div class="wrap">  
    <div class="center"></div>  
</div>  
  

CSS Code复制内容到剪贴板

/* css */ .wrap { position: relative; background: yellow; width: 200px; height: 200px;} .center { position: absolute; background: green; top:50%; left:50%; -webkit-transform:translate(-50%,-50%); transform:translate(-50%,-50%); width: 100px; height: 100px;   
}   
  

兼容性:ie9以下不支持 transform,手机端表现的比较好。

方法四:flex;align-items: center;justify-content: center

XML/HTML Code复制内容到剪贴板

<!– html –>  

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表