Delete the automatic height adjustment using CSS

I am experiencing an issue with images in HTML where the width and height are set, but a stylesheet is overriding them with "height: auto."

Is there a way to reset or override this CSS property so that the specified height in HTML takes precedence?

HTML:

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

CSS:

img {
  height: auto;
}

JSFiddle

Additional information:
I am implementing lazy loading for images in PrestaShop eCommerce, where I have limited control over the environment.
Upon document ready, I set the image source to a transparent pixel. However, as seen in the JSFiddle example, the image appears squared instead of respecting the width and height specified in HTML.
This discrepancy is due to the "height: auto" property causing the height to adjust according to the width, leading to visual inconsistencies and bugs when scripts modify the height incorrectly.

Answer №1

This solution may seem simple, but I wholeheartedly believe it's the exact answer you've been searching for...


It's impossible.

After defining a height for an img in CSS, any HTML declaration is immediately disregarded. There's no way within the CSS to then override that declaration and utilize the height specified in the HTML because terms like initial pertain to properties determined by CSS, not HTML attributes.

Refer to this guide on CSS Height, outlining all Property Values: *Experimental/non-supported values omitted

height: auto | length | % | inherit | initial

If you try to redefine the height of img using any of these property values, they won't be effective - I've tested each one individually to confirm this.

  • length and % necessitate a specified height, precisely what you're aiming to avoid

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

  • inherit lacks a parent to inherit from, thus resorting to the default value of auto


Your sole option is to override the height in CSS, utilizing inline styles (suggested by Carter)...

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

Alternatively, employ selectors such as IDs or classes...

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

Or, if you require JS to automatically generate overrides, consider implementing a jQuery solution like this:

$("img").each(function() {        //Loop through all images
    var $t = $(this);             //$t represents the current iteration
    var ht = $t.attr("height");   //Retrieve the HTML height
    ht = ht ? ht+"px" : "auto";   //Add "px" if HTML height is defined | Use "auto" otherwise
    $t.css("height", ht);         //Apply the height to the current element
});

This script loops through all images on the page and assigns a CSS height corresponding to the HTML height. In the absence of an HTML height, it defaults to height: auto;.

Answer №2

To take precedence over existing CSS rules, you can utilize inline CSS properties. Remember that in HTML, the height attribute of an image element will not override CSS settings. To enforce a specific image height, you must employ inline styles like this:

<img src="..." width="350" style="height:150px;" />

Answer №3

It is advised not to set a global height for all img tags by overriding it. Instead, consider changing the declaration to:

.img-auto-height {
  height: auto;
}

Simply add class="img-auto-height" wherever you want an image to have automatic height.

Answer №4

If you need to change the height, try using this:

height: unset;

This is supported in most browsers except for Internet Explorer

Answer №5

Although it may not be a direct removal, there are several alternative approaches you can consider.

  • One option is to adjust the height through the parent element

div img { height: 150px; }

  • Alternatively, you can use a pseudo-selector

img:nth-child(1n){
  height: 150px;
}

img:nth-child(1n){
  height: 150px;
}
img {
  height: auto;
}  
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="width="350" height="150">

Answer №6

When implementing lazy loading for all images on a website, it is important to adjust the image size dynamically once the lazy loading process is in effect:

img:not(.lazy) {
  height: auto;
}

As the actual image loads, the HTML attribute height="X" will be applied, aligning closely with the true dimensions of the image.

To prevent any shifting effects during loading, using a base64 image placeholder with a similar aspect ratio to the final image can be beneficial (typically a 2:1 ratio works better than a square pixel ratio).

Answer №7

Following in the footsteps of J. Alba, I have also opted for the following solution:

img:not(.no-height-auto) {
  height: auto;
}

This ensures that most images will have a height set to auto, which is typically my desired outcome:

<!-- this image will adjust its height automatically -->
<img src="my-img.jpg" height="600" width="800" />

If there is a specific image where I do not want the height to be auto-adjusted, I simply apply the class:

<!-- this image will maintain a fixed height of 600px -->
<img src="my-img.jpg" class="no-height-auto" height="600" width="800" />

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Inconsistencies with Colorbox behavior in an external HTML document

Encountering a strange issue with colorbox while attempting to display a "div" element from another HTML file. The code functions perfectly, except for the final "div" in the external file. The structure of my external file is as follows; div1 img par ...

Using classes to override CSS

I've been going through the Material UI Overrides documentation in an attempt to customize the color of each radio button, but I'm having trouble grasping it conceptually. If I start with Material UI's default setup for radio buttons, how ca ...

Steps to update the action attribute in a form element upon clicking a button

Within the following code snippet, there are 3 buttons - update, back, and delete. Depending on which button is clicked, the $page variable should be assigned to the action attribute in the form element, with the posted data being sent accordingly. <f ...

Responsive design for iPads and smartphones is essential in ensuring a seamless user

Currently in the process of creating my own personal website, I have been diligently using Chrome Canary to ensure that all my media queries are properly set up. While everything looks great on Canary and functions well in various device modes within the b ...

The PHP script fails to execute within HTML elements

Hey there! I'm currently working on designing my own error page, which involves extracting some data from the URL. At the top of my error.php file, here is the code I have: <?php $error_message = $_GET["error_message"]; if(!$error_message) { ...

Responsive design in Bootstrap(-Vue) with compact input fields

I am currently working on creating an input form with small fields and signs between them. https://i.sstatic.net/THjhs.png Right now, I am using a combination of classic HTML and Bootstrap-Vue, as shown in the screenshot. It is functional, but the issue ...

Manipulating HTML content with Javascript Array

Is there a way to retain Javascript context from an array? Any suggestions for improving this code? SAMPLE: <html> <script type="text/javascript"> var rand = Math.floor(Math.random() * 6) + 1; var i = Math.floor(Math.random() * 6) + 1; var ...

Moving image transitions on the screen using CSS3

Looking for a demonstration of an image sliding in from the left of the screen, pausing in the center for a brief moment, and then continuing across the page. Any ideas on where to find this? Appreciate it, Adam ...

The performance of my SVG Filter is dismal

Here is the SVG filter I am using: <svg style="visibility: hidden; height: 0; width: 0;"> <filter id="rgbShift"> <feOffset in="SourceGraphic" dx="1" dy="-1" result="text1" /> <feFlood flood-color="#FF0000" result=" ...

Reinitializing AngularJS form controls

Check out this codepen example: http://codepen.io/anon/pen/EjKqbW I'm trying to reset the form elements when the user clicks on "Reset". The div elements f1,f2,f3 should be hidden and the searchText box cleared. However, the reset button is not trig ...

What are some solutions to correct a tab layout that is utilizing absolute positioning?

Although I understand how absolute positioning works, it is currently disrupting the layout in this particular case. Using min-height with media queries for various screen sizes seems like a viable solution, but it's not foolproof considering that the ...

The positioning of drawings on canvas is not centered

I'm facing an issue while attempting to center a bar within a canvas. Despite expecting it to be perfectly centered horizontally, it seems to be slightly off to the left. What could possibly be causing this discrepancy? CSS: #my-canvas { border: ...

Stylesheet specific to Internet Explorer not loading

My Rails application (link) is experiencing display bugs in Internet Explorer. I am trying to fix these bugs by making changes in the app/views/layouts/application.html.haml file where I have included: /[if IE] ...

Tips for creating canvas drawings in GWT

Here's a simple jQuery code to draw a triangle in a canvas element that is 40 by 40: var context1 = $("#arrow_left").get(0).getContext('2d'); context1.beginPath(); context1.moveTo(25,0); context1.lineTo(0,20); context1.lineTo(25,40); contex ...

The Art of Positioning Containers in CSS

I am facing some issues with my CSS. In the JSP webpage, I have a container styled with a div that works perfectly. However, when I insert another div tag to style certain elements, those elements end up outside of the container for some reason. Below is ...

Displaying a preloaded image on the canvas

Once again, I find myself in unfamiliar territory but faced with the task of preloading images and then displaying them on the page once all elements (including xml files etc.) are loaded. The images and references are stored in an array for later retrie ...

Retrieve the Latest Information from the Asp.Table

My table setup is as follows: <asp:Table ID="model" runat='server'> <asp:TableRow> <asp:TableHeaderCell class="col-xs-2"> Name </asp:TableHeaderCell> <asp:TableHeaderCell class="col- ...

Incorporating dynamic content changes for enhanced user experience can be achieved more effectively with AngularJS

I am utilizing a REST service to retrieve information for a banner. The goal is to dynamically update the slider on the main page using this data. Currently, I am using $http.get to fetch the data, and then implementing interpolation with additional ng-if ...

How can one generate an HTML element using a DOM "element"?

When extracting an element from an HTML page, one can utilize a DOM method like .getElementById(). This method provides a JavaScript object containing a comprehensive list of the element's properties. An example of this can be seen on a MDN documentat ...

How to interrupt a JQuery animation and restart it from the middle?

Currently, I am tackling my first JQuery project and facing a challenge. As the user mouseleaves the .container, the animation does not reset but continues as if they are still within it. My goal is to have the animation revert in reverse if the user decid ...