Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style <img> to read dimensions from its HTML attributes, not CSS

Tags:

html

css

image

Once width or height properties have been tampered with through CSS, how do you cancel those styles and tell images to read dimensions from their HTML attributes again?

The initial value of width and height is auto, but setting it explicitly doesn't work:

img {
  height: 200px;
}

/* ... */

img {
  height: auto;
}

It will just make images ignore their HTML attributes completely.

like image 269
silvenon Avatar asked Dec 03 '25 17:12

silvenon


2 Answers

If you have access to the initial CSS that sets the height on the img, then for CSS3 browsers, you can modifiy it to this:

img:not([width]):not([height]) {
    height: 200px;
}

It uses the :not to "not" apply it if the image has either a width or a height attribute. You can see results in this fiddle. This implies that you always want an attribute to take precedence over the above CSS. Then, if you actually want to apply a change via CSS, you would need to apply a class or something to the img, like so:

<img src="blah" class="specialCase" />

img.specialCase {
    height: 200px;
}

Which overrules height but not width settings as this fiddle shows.

like image 101
ScottS Avatar answered Dec 06 '25 09:12

ScottS


I'm afraid it's not possible to cancel a CSS rule this way in order to make an element fall back to its HTML presentational attributes. This is because presentational attributes are mapped to CSS rules with precedence so low that even a CSS rule with a * selector will permanently override them.

Setting a property to its initial value doesn't inherently cancel anything out; it just creates a rule which sets it to the default value that's stated by the spec and participates in the cascade like any other rule. In this particular case, setting height: auto doesn't work because all it does is override the values that were originally provided by the HTML attributes and by the previous CSS rule with... well, auto.

One possible alternative I can think of is to use JavaScript to delete the offending declarations from the document's stylesheet(s), but I'm not sure if that actually works — I haven't tried it.

like image 26
BoltClock Avatar answered Dec 06 '25 08:12

BoltClock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!