img标签src不给路径就会出现边框

<img/>src加载失败或没有给的,浏览器会自动给img加上边框。
如下图这样:

产品觉得影响美观,一定要pass掉。

原码是这样:

.ctn{
	position: relative;
	 2.8rem; 
	height: 2.8rem;
	border-radius: 3px;
	overflow: hidden;
	background: #FFF;
}
.ctn .title{
	position: absolute;
	top: 0;
	 2.8rem; 
	height: 2.8rem;
	background:rgba(0,0,0,.35) ;
	color: #FFF;
	font-size: .52rem;
	font-weight: bold;
	padding:0 .4rem;
}
.ctn img{
	 2.6rem;
	height: 2.2rem;
	margin: .3rem auto;
	object-fit: cover;
	background: url(images/120X120.jpg?201608012) no-repeat center;
	background-size: 2.2rem;
}
<div class="ctn">
    <div class="title sn-flex center">
	    <p>休闲西装</p>
    </div>
	<img src=""/>
</div>

百度一下,在知乎上找到了解决方案,链接在这https://www.zhihu.com/question/27426689

基于能用css实现就不用js的原则,选择了以下的解决方案:
img包个div

<div class="ctn">
    <div class="title sn-flex center"><p>收腰款</p></div>
    <div class="img-ctn">
         <img  src="temp/app_200x200.jpg"/>
    </div>
</div>
.ctn .img-ctn{
	 2.6rem;
	height: 2.2rem;
	margin: .3rem auto;
	overflow: hidden;
}
.ctn .img-ctn img{
	 -webkit-calc(2.6rem + 2px);
	height: -webkit-calc(2.2rem + 2px);	
	 calc(2.6rem + 2px);
	height: calc(2.2rem + 2px);
	background: url(images/120X120.jpg?201608012) no-repeat center;
	background-size: 1.8rem;
	margin: -1px;
	object-fit: cover;	
}

but,有问题,无图片时上下的border是隐藏了,左右无论怎么样都隐藏不了,暂时没查出来问题,于是改成了这样:

.ctn .img-ctn{
	 2.6rem;
	height: 2.2rem;
	margin: .3rem auto;
	overflow: hidden;
	background: url(images/120X120.jpg?201608012) no-repeat center;
	background-size: 1.8rem;
}
.ctn .img-ctn img{
	 inherit;
	height: inherit;
	object-fit: cover;
}
/*无src隐藏*/
.ctn .img-ctn img[src='']{
	visibility: hidden;
}

后来,在控制台调试时,忽然灵光乍现,FUCK,是reset样式的问题。

原来,base.css
img做了这个

img {
    max- 100%;
}

hehe,重新又改成这样:

.ctn .img-ctn{
	 2.6rem;
	height: 2.2rem;
	margin: .3rem auto;
	overflow: hidden;
}
.ctn .img-ctn img{
	 -webkit-calc(2.6rem + 2px);
	height: -webkit-calc(2.2rem + 2px);	
	 calc(2.6rem + 2px);
	height: calc(2.2rem + 2px);
	background: url(images/120X120.jpg?201608012) no-repeat center;
	background-size: 1.8rem;
	margin: -1px;
    /*就是这货*/
	max- none;
	object-fit: cover;	
}

ok,提交给开发,终于可以偷懒一会了。

however,改变来的太快。开发发来了一张图:

去开发机上调试一下,瞬间感受到了深深的恶意。

原来图片的背景图层是透明的,盒子模型的渲染层级是color>src>background-image>background-color,图片空白区域透明自然就显示背景图片了。

img{
    background: red url(images/120X120.jpg?201608012) no-repeat center;
}
<img src=".png">

感觉自己的洪荒之力已经用完了。。。。

at the end,为了规避这种图片出现,直接不给背景图片了,还是通过模板引擎来判断吧

<img src="{$src||'images/120X120.png'}"/>

多好,一下子就解决了。

白白绕了这么一大圈

原文地址:https://www.cnblogs.com/phillyx/p/5766247.html