Search code examples
htmlcssheight

Remove height auto using css


I have images which have width and height in html but there is also a stylesheet affecting these images with height auto

How to reset/override this property using css so that the html height comes into effect?

Html:

<img src="..." width="350" height="150" />

Css:

img {
  height: auto;
}

JSFiddle

More info:
I'm implementing img lazyload in an environment I don't fully control (PrestaShop eCommerce).
On document ready, I'm setting the img src to a transparent pixel but as the js-fiddle shows, the image comes squared althought it doesn't have the same width/height in html.
The height is following the width because of the height auto prop.
This leads to "jumping" and also to some bugs when a script sets the height style to the wrong value.


Solution

  • While this answer feels somewhat cheap, I truly believe it's the answer you're looking for...


    You can't.

    Once you've set a height on the img in CSS, the HTML declaration gets immediately overridden. There is no way further along in the CSS to then ignore that declaration and use the HTML-specified height, because things like initial refer to CSS-defined properties (source), not associated HTML attributes.

    See this reference for CSS Height, which lists all Property Values: *Experimental/non-supported values ommitted

    height: auto | length | % | inherit | initial

    If you attempt to re-define the height of img using any of the above property values, they will not work - I've just tried each and every one to be sure.

    • length and % require a defined height, which seems to be the exact thing you're trying to avoid

    • initial will just grab the initial CSS declaration of height: auto;

    • inherit doesn't have an ancestor to inherit from, therefore it falls back to the default of auto


    Your only real choice is to override the height in CSS, either using in-line styles (as suggested by Carter)...

    <img style="height: 150px;" />
    

    Or by applying selectors like ID's or classes...

    <img id="my_image" />
    
    #my_image {
        height: 150px;
    }
    

    Or, if you need to use JS to auto-generate the overrides, consider something like this jQuery solution:

    $("img").each(function() {        //Loop through all images
        var $t = $(this);             //$t is the current iteration
        var ht = $t.attr("height");   //Get the HTML height
        ht = ht ? ht+"px" : "auto";   //If HTML height is defined, add "px" | Else, use "auto"
        $t.css("height", ht);         //Apply the height to the current element
    });
    

    This loops through all images on the page and applies a CSS height to match the HTML height. If there is no HTML height, it will use height: auto;.