Home  >  Article  >  Web Front-end  >  【CSS】响应式图片_html/css_WEB-ITnose

【CSS】响应式图片_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:46:201330browse

原图:(宽1680px,高1050px)


可是,我们平时做网站的时候当【CSS】响应式图片_html/css_WEB-ITnose中的图片大于可是窗口时,就会出现横的滚动条、图片被截断的情况,如下图所示:


这时候我们可以使用响应式技术来解决:

响应式图片就是当浏览器屏幕窗口大小改变时,图片会随着窗口大小的改变而改变,不会出现图片被截断或出现横滚动条。

HTML代码:

       <img src="1.jpg" alt="””/">

CSS代码:

img{		width: 100%;		   /*设定为百分比那就OK*/		max-width: 100%;    /*为了保证图片不被拉伸,可加上此CSS属性*/	}

效果:


上面示例是插入img标签的情况,那么背景图片是怎么处理呢?

HTML代码:

    <div class="backgroundImgShow">    	<p class="text">12111111111111111444444444444444444444444444445555555555555</p>    </div>

CSS代码:

body,div,p{		margin: 0;		padding: 0;	}.backgroundImgShow {		background: url(1.jpg) no-repeat 50% 50%;	}.text{		color: white;		word-wrap: break-word;		font-size: 30px;	}
一般情况下,当内容的高度小于背景图片的高度时,背景图片就不能全部显示,如下图所示:


这时候我们可能会想到为内容区设定与背景图片同样的高度,如我的示例图片是1680px*1050px,那么我的CSS height值可设为1050px;

body,div,p{		margin: 0;		padding: 0;	}	.backgroundImgShow {		background: url(1.jpg) no-repeat 50% 50%;		<strong><span   style="max-width:90%"> -webkit-background-size: 100%;		background-size: 100%;		height: 1050px;</span></strong>	}	.text{		color: red;		word-wrap: break-word;		font-size: 30px;	}
这样背景图片就可以等比例缩放了,但图片距离浏览器顶部却有1050px的空白高度,如图:


这时候去掉高度,且修改CSS代码为:

body,div,p{		margin: 0;		padding: 0;	}	.backgroundImgShow {		background: url(1.jpg) no-repeat 50% 50%;		 -webkit-background-size: 100%;		background-size: 100%;<span style="white-space:pre">		</span><strong><span style="color:#ff0000;">padding-top: 62.5%; 	/* 1050/1680=0.625 即高度除以宽度,可以解决背景图片的比例问题 */</span></strong>	}	.text{		color: red;		word-wrap: break-word;		font-size: 30px;	}
效果如下:


可以看到图片上面仍然会出现一点白边,且文字并不完全在图片里面,这时候我们可以更进一步优化,我们可以把background-size: 100%;修改为background-size: cover;意思就是背景图片填满包装它的容器,并且按比例缩放。效果图:


可是文字由于上面设置了padding-top:62.%;所以会有很大的上边距,可以设置margin-top:-62.5%;来取消边距。最终图:


最终CSS代码:

body,div,p{		margin: 0;		padding: 0;	}	.backgroundImgShow {		background: url(1.jpg) no-repeat 50% 50%;		 -webkit-background-size: cover;		background-size: cover;		padding-top: 62.5%; 	}	.text{		color: red;		margin-top: -62.5%;		word-wrap: break-word;		font-size: 30px;	}

注:虽然能够通过响应式的方式使得图片在不同大小的屏幕也能等比例缩放,大图片(分辨率高)在较小的屏幕上加载浏览时(如手机),有WiFi的时候加载速度区别不大,但是没WiFi的情况下要加载这么大的图片就很吃力了。这时候可以使用媒体查询,使用较小(分辨率低)的图片代替大图,加载就会快一点,提升用户体验。


Author:致知

Sign:路漫漫其修远兮,吾将上下而求索。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn