I want to use different sized images depending on the webpage size. For example, my images has two different sizes:
<img src="images/img1.jpg" data-big="images/img1.jpg" data-small="images/img1small.jpg" alt=""></img>
The data-small image has a width of 100px.
@media (max-width:600px) {
img[data-small] {
content: attr(data-small, url); <-- not working
/*width:10px;*/ <-- this would work
}
}
I testet it on Firefox 37.0.1, Chrome 42.0.2311.90 m and IE 11
If I resize the browser to a very small width (< 600px), the image is still the same.
content attr is used in :before and :after selectror. How ever you can use media query.
<img src="images/img1.jpg" class="big_image" alt="">
<img src="images/img1small.jpg" class="small_image" alt="">
and the css will be
@media (max-width:600px) {
.small_image{ display:block }
.big_image{ display:none }
}
@media (min-width:601px) {
.small_image{ display:none }
.big_image{ display:block }
}
Image tags work using the src
attribute. In order to change the image, you need to change the src
attribute, which you cannot do with CSS.
content: attr(data-small, url);
does not change the src
attribute. You're setting the content
of the element to the data-small
attribute, which does nothing on an img
tag. As I mentioned, you cannot change the src
attribute with CSS .
I'd advise using srcset
. This will gracefully degrade in old browsers, and will work well in new browsers.
<img src="images/img1small.jpg" srcset="images/img1big.jpg 600w" alt="" />
Otherwise, user1936285's solution also works well.
Maybe you can use CSS background-image: url("image.png")
instead of <img>
Something like this:
@media (max-width:600px) {
.container{ background-image: url("imagebig.png") }
}
@media (min-width:601px) {
.container{ background-image: url("imagesmall.png") }
}
采用:
content: url(attr(data-small));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.