CSS如何设置不同屏幕宽度时某个DIV容器里显示不同的图片?

html-css09

CSS如何设置不同屏幕宽度时某个DIV容器里显示不同的图片?,第1张

中间这句话,必须要

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<style rel="stylesheet">

@media (max-width: 768px){

.hello{

}小余768

@media(min-width:769px){

}大于768

</style>

图片的话写个宽度,高度自动。如果是背景图的话,就不一样

可以有多种方法实现的。比如可以给每个img设置不同的ID:

<img id=p1 src="1.jpg"/><img id=p2 src="2.jpg"/><img id=p3 src="3.jpg"/>

<style>

#p1 {border:1px solid #f00}

#p2 {border:1px solid #0f0}

#p3 {border:1px solid #00f}

</style>

或者是不同的class:

<img class=p1 src="1.jpg"/><img class=p2 src="2.jpg"/><img class=p3 src="3.jpg"/>

<style>

.p1 {border:1px solid #f00}

.p2 {border:1px solid #0f0}

.p3 {border:1px solid #00f}

</style>

还有一种更灵活的方式,但需要浏览器支持css3:

<img src="1.jpg"/><img src="2.jpg"/><img src="3.jpg"/>

<style>

img:nth-of-type(1) {border:1px solid #f00}

img:nth-of-type(2) {border:1px solid #0f0}

img:nth-of-type(3) {border:1px solid #00f}

</style>

这种方法还有多种灵活的处理方式,比如:

img:nth-of-type(odd) 会选择所有单数的图片(第1张、第3张、第5张……)

img:nth-of-type(even) 会选择所有双数的图片(第2张、第4张、第6张……)

img:nth-of-type(2n) 也是选择双数

img:nth-of-type(2n+1) 也是选择单数

img:nth-of-type(3n+1) 从第1张算起每3张取出1张图片(第1张、第4张、第7张……)

img:nth-of-type(5n+3) 从第3张算起每5张取出1张图片(第3张、第8张、第13张……)

除了这个,css还有几十种不同的选择器,你百度搜一下 css选择器 就知道了。

可以使用:Background-size属性

语法:

background-size :[ <length> | <percentage> | auto ]{1,2} | cover | contain

取值:

<length>:

由浮点数字和单位标识符组成的长度值。不可为负值。

<percentage>:

取值为0%到100%之间的值。不可为负值。

说明:

设置背景图片的大小。

指定背景大小,以象素或百分比显示。当指定为百分比时,大小会由所在区域的宽度、高度,以及background-origin的位置决定。还可以通过cover和contain来对图片进行伸缩。

示例代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html charset=utf-8" />

<title>Background-size</title>

</head>

<body>

<div style="border: 1px solid #CCCCCC padding:90px 5px 10px background:url(http://webteam.tencent.com/wp-content/themes/teamblog/img/gg.png) no-repeat  -webkit-background-size: 100% 80px -o-background-size: 100% 80px ">这里的 <code>background-size: 100% 80px</code>。 背景图片将与DIV一样宽,高为80px。</div>

</body>

</html>