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

2020-05-10 11:21:48易采站长站整理

} .center { background: green; width: 100px; height: 100px; margin: auto;   
}   
  

如果是PC端,要考虑兼容性的话。方法六是不错滴,也就是纯position。

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

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

CSS Code复制内容到剪贴板

/* css */ .wrap { background: yellow; width: 200px; height: 200px; position: relative;   
} /**方法一**/ .center { background: green; position: absolute; width: 100px; height: 100px; left: 50px; top: 50px;     
     
} /**方法二**/ .center { background: green; position: absolute; width: 100px; height: 100px; left: 50%; top: 50%; margin-left:-50px; margin-top:-50px;   
}   
  

如果PC端的中间的元素高度不固定,那么就用方法七即可,代码就不复制了。

这种css元素垂直的如果真的要总结起来,应该有十几二十几种。不过也没必要全部掌握吧,只要大概了解一些,用起来没有副作用就行。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持软件开发网。