您现在的位置是:网站首页> 编程资料编程资料

css让容器水平垂直居中的7种方式_CSS教程_CSS_网页制作_

2021-09-12 1146人已围观

简介 这篇文章主要为大家详细介绍了css让容器水平垂直居中的7种方式,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

方法一:position加margin

XML/HTML Code复制内容到剪贴板
  1. <div class="wrap">  
  2.     <div class="center">div>  
  3. div>  
  4.   
CSS Code复制内容到剪贴板
  1. /**css**/ .wrap { width200pxheight200pxbackgroundyellowpositionrelative;   
  2. } .wrap .center { width100pxheight100pxbackgroundgreenmarginautopositionabsoluteleft: 0; rightright: 0; top: 0; bottombottom: 0;   
  3. }  

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

方法二:diaplay:table-cell

XML/HTML Code复制内容到剪贴板
  1.   
  2. <div class="wrap">  
  3.      <div class="center">div>  
  4. div>  
  5.   
CSS Code复制内容到剪贴板
  1. /*css*/ .wrap{ width200pxheight200pxbackgroundyellowdisplaytable-cellvertical-alignmiddletext-aligncenter;   
  2. } .centerdisplayinline-blockvertical-alignmiddlewidth100pxheight100pxbackgroundgreen;   
  3. }   
  4.   

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

方法三:position加 transform

XML/HTML Code复制内容到剪贴板
  1.   
  2. <div class="wrap">  
  3.     <div class="center">div>  
  4. div>  
  5.   
CSS Code复制内容到剪贴板
  1. /* css */ .wrap { positionrelativebackgroundyellowwidth200pxheight200px;} .center { positionabsolutebackgroundgreentop:50%; left:50%; -webkit-transform:translate(-50%,-50%); transform:translate(-50%,-50%); width100pxheight100px;   
  2. }   
  3.   

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

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

XML/HTML Code复制内容到剪贴板
  1.   
  2. <div class="wrap">  
  3.     <div class="center">div>  
  4. div>  
  5.   
CSS Code复制内容到剪贴板
  1. /* css */ .wrap { backgroundyellowwidth200pxheight200pxdisplay: flex; align-items: centerjustify-contentcenter;   
  2. } .center { backgroundgreenwidth100pxheight100px;   
  3. }   
  4.   

移动端首选

方法五:display:flex;margin:auto

XML/HTML Code复制内容到剪贴板
  1.   
  2. <div class="wrap">  
  3.     <div class="center">div>  
  4. div>  
CSS Code复制内容到剪贴板
  1. /* css */ .wrap { backgroundyellowwidth200pxheight200pxdisplay: flex;    
  2. } .center { backgroundgreenwidth100pxheight100pxmarginauto;   
  3. }   
  4.   

移动端首选

方法六:纯position

XML/HTML Code复制内容到剪贴板
  1.   
  2. <div class="wrap">  
  3.     <div class="center">div>  
  4. div>  
  5.   
CSS Code复制内容到剪贴板
  1. /* css */ .wrap { backgroundyellowwidth200px
-六神源码网