Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Responsive images in a fluid-width table (max-width)

Consider the following piece of code:

HTML:

<div>
    <img src="http://placehold.it/600x150" />
</div>

CSS:

div { max-width: 200px }
img { max-width: 100%  }​

The image will never be wider than 200px, regardless of its native size. So far so good.

Here's the fiddle: http://jsfiddle.net/PeAAb/


However, if the parent element has its display set to table:

div { max-width: 200px; display: table }

the image magically expands to its native width, expanding the table with it.

Here's the fiddle: http://jsfiddle.net/PeAAb/1/


Same happens with an actual table: http://jsfiddle.net/PeAAb/2/


Question: Is this expected behavior? If so, what can be done to work around this issue?

Setting the parent's width (even a percentage-based width) instead of max-width correctly squeezes the image back into its box, but is not a solution. I need the parent to be fluid (I'm using this for the main structure of the site, so that I can have the sidebar HTML appear after the main content in the source, but with the sidebar being fixed width).

Also, setting table-layout to fixed seems to have no effect here.

like image 517
Joseph Silber Avatar asked Aug 08 '12 21:08

Joseph Silber


People also ask

How do I make my image fully responsive?

To make an image responsive, you need to give a new value to its width property. Then the height of the image will adjust itself automatically. The important thing to know is that you should always use relative units for the width property like percentage, rather than absolute ones like pixels.

What is responsive image?

Responsive images are the set of techniques used to load the right image based on device resolution, orientation, screen size, network connection, and page layout. The browser should not stretch the image to fit the page layout, and loading it shouldn't result in time & bandwidth wastage.


1 Answers

The problem here is that a table (or a div set to behave like a table) is not a block element, and max-width only applies to block elements. My only suggestion to you is to wrap the table element in a div with display: block; set.

Here's the fiddle in case you're interested: http://jsfiddle.net/PeAAb/4/

like image 163
David Vasquez Avatar answered Oct 03 '22 18:10

David Vasquez