Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image Set Width Height Attributes in HTML, Set Width 100% in CSS

Tags:

html

css

I have an image whose size I know.

<img class="example" src="img.jpg" width="1024" height="768" />

I want to have the width and height attributes set so it can layout where the image will be before it's downloaded. The image may take a second or two to come in, so when it does, I don't want the page to suddenly jump.

However, I also want the image to have width: 100%. Is there a way to achieve this using CSS?

I tried

.example {
    width: 100%;
    height: auto;
}

However, this ignores the aspect ratio I specified in the HTML. Is there a way I can use the width and height attributes defined in the HTML to keep the aspect ratio, but have the image to have width: 100% (i.e. the width of the parent)?

I don't want to use JS to achieve this, I don't want to hard code the proportions in CSS, and I'd rather not do any margin/padding hacks to achieve this.

Edit

Really, I'm just seeing if there's a better way of doing it than this,

https://jsfiddle.net/s6gkonbh/

like image 613
Jacob Parker Avatar asked Jun 22 '26 11:06

Jacob Parker


1 Answers

[Update: updated link to fix broken external image url]

JSFiddle Demo

<div style="width:356px; height:452px; background-color:yellow">
<img class="example" src="https://live.staticflickr.com/1427/1370476027_aaf0621679.jpg" width="100%" />
</div>

just provide the width and height to the parent container division which will occupy the space of the image's dimensions while the image will load.

and set the width of the image to 100% and it will take height according to aspect ratio. Just set the background color of your parent div to white or something to blend with the background.

JSFiddle Demo


HTML:

<div style="width:500px; height:300px; background-color:yellow">
  <img class="example" src="http://www.finnchat.com/app/uploads/2015/10/Blogi44_metakuva.jpg" width="100%" />
</div>

NB: image copyrights are with their respective owners.

like image 131
Himanshu Avatar answered Jun 24 '26 23:06

Himanshu