css子元素在父元素居中显示
今天在做开发任务的时候遇到了一个最基本的子集div在夫级div中水平垂直居中的问题,就总结了下我们经常用到的方法(此外由于自己能力问题,有误望指出批评) 一:通过定位来实现 1.如果子元素的大小是已知的,可以通过对子元素定位,并且margin值分别减去自己宽高的一半(上码) <style> .father { width: 200px; height: 200px; border: 1px solid red; position: relative; } .child { width: 100px; height: 100px; background-color: #00BCBC; position: absolute; top: 50%; left: 50%; margin-top: -50px; margin-left: -50px; } </style> <body> <div class="father"> <div class="child"></div> </div> </body> 效果图: 2.我们子元素的大小不明确的情况下,有两种实现方式 (1)用margin为auto实现 <style> .father { width: 200px; height: 200px; border: 1px solid red; position: relative; }