div中img依据不同分辨率居中显示,超出部分隐藏
程序员文章站
2022-04-09 08:05:06
...
在做banner居中时 碰到的问题,知道可以用背景图实现居中显示,但是内心是想深究下的,故找到几种办法收集一下,后面两种真的是奇技淫巧
来着下面两处
https://www.zhihu.com/question/39742237
https://www.v2ex.com/t/187544
- flex
- position:absolute negative margin
- background-image background-size background-position
4.父元素position:relative,子元素
{ transform: translate(-50%,-50%);
position: absolute;
top: 50%;
left: 50%; }
父子元素都可以不定宽度。translate百分比根据自身高度宽度。只在UC浏览器及overflow:hidden叠加时会有问题
5.p元素 和隐藏的img扩充父元素的宽高
http://nec.netease.com/library/141122
<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;居中
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; }
上一篇: 超简单的图片水平垂直居中
下一篇: mysql创建表的sql语句