0

I've got an image that has 90% width, but with a max width of 640px. I want to set a specific style when the max width is reached. So, I was thinking about a style that is applied depending on the width. Here there's a similar question:

CSS targeting specific images

But I don't have a width attribute. How can I achieve this (without using js, if possible)?

Community
  • 1
  • 1
ufo
  • 674
  • 2
  • 12
  • 35

3 Answers3

2

To further user3127242, you can use media queries to add landmarks where the image should change. In order to effectively change the image source, you should also consider using a div with background-image set. Example:

HTML:

<div id="fancy"></div>

CSS:

#fancy {
    background: transparent url(...) 0 0 no-repeat;
    width: 400px
}

@media only screen and (min-width:400px) {
    background-image: url(image1.jpg); 
}
@media only screen and (min-width: 500px) {
    background-image: url(image2.jpg);
}

Example fiddle here: http://jsfiddle.net/27UjQ/2/

1

The only way without js of which I can think is using mediaQueries. Doing the math I calculated the size of your image will be 640px, when the screen's resolution is 1064. Therefore you will need to add this mediaQueries code to your css, which changes the img's style when this resolution is reached

@media only screen and (min-width:768px) {
    /* Your changes to the image's style */

}

Here's a link. Try resizing the window to see the changes when the certain width is reached.

Boyan Hristov
  • 1,067
  • 3
  • 15
  • 41
  • This was my first thought. But I already use media queries for dinamically change the number of columns in the layout. So it is quite difficult to calculate the exact screen resolution. I'll give a try or I'll adopt javascript for this... I hoped there was something similar to mediaqueries, like `img and (width:400px) { something }`. – ufo Dec 22 '13 at 14:29
  • Well CSS is used to style your page and mediaQueries to make it look great on all resolutions. Therefore there is no way to check for an image's width in CSS. If you have one or two images, you shouldn't have any problems using mediaQueries. Otherwise you must use javascript ;) – Boyan Hristov Dec 22 '13 at 14:35
0

It would be great if you could provide us with a working example or your code. But try the following:

img {
    width: 90%;
    max-width: 400px; /* just an example */
}
Uzair Hayat
  • 518
  • 1
  • 8
  • 21
  • Thank you for your answer. This is what I already have. What I want now is something that in pseudocode looks like this: `If (img.width = 400px) Then img.something = x End If` Thank you. – ufo Dec 22 '13 at 14:21