在作banner居中時 碰到的問題,知道能夠用背景圖實現居中顯示,可是心裏是想深究下的,故找到幾種辦法收集一下,後面兩種真的是奇技淫巧瀏覽器
來着下面兩處flex
https://www.zhihu.com/question/39742237spa
https://www.v2ex.com/t/187544.net
4.父元素position:relative,子元素code
{ transform: translate(-50%,-50%);
position: absolute;
top: 50%;
left: 50%; }orm
父子元素均可以不定寬度。translate百分比根據自身高度寬度。只在UC瀏覽器及overflow:hidden疊加時會有問題blog
5.p元素 和隱藏的img擴充父元素的寬高圖片
http://nec.netease.com/library/141122it
<div class="m-demo"> <p> <img src="http://nec.netease.com/img/s/1.jpg" class="hidden"/> <img src="http://nec.netease.com/img/s/1.jpg" alt=""/> </p> </div> <div class="m-demo"> <p> <img src="http://nec.netease.com/img/m/1.jpg" class="hidden"/> <img src="http://nec.netease.com/img/m/1.jpg" alt=""/> </p> </div> <div class="m-demo"> <p> <img src="http://nec.netease.com/img/l/1.jpg" class="hidden"/> <img src="http://nec.netease.com/img/l/1.jpg" alt=""/> </p> </div>
/* 圖片居中溢出隱藏 */ .m-demo{position:relative;width:300px;height:300px;overflow:hidden;border:1px solid #ddd;} .m-demo p{position:absolute;top:50%;left:50%;margin:0;padding:0;} .m-demo img{position:absolute;top:-50%;left:-50%;display:block;} .m-demo img.hidden{visibility:hidden;position:static;}
6.將a設置top: -100%; bottom: -100%; left: -100%; right: -100%;擴充至原來的3倍,而後text-align: center;居中io
http://dabblet.com/gist/e191e05066016cb040d4
<div class="banner"> <a href="#"><img src="//placehold.it/500x300" alt=""/></a> </div> <div class="banner"> <a href="#"><img src="//placehold.it/100x100" alt=""/></a> </div>
.banner { width: 300px; height: 200px; overflow: hidden; position: relative; } .banner > a { position: absolute; top: -100%; bottom: -100%; left: -100%; right: -100%; text-align: center; } .banner > a:before { content: ""; display: inline-block; vertical-align: middle; height: 100%; } .banner > a > img { vertical-align: middle; }