这种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 –>
新闻热点
疑难解答