Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Images not responsive by default in Twitter Bootstrap 3?

Bootstrap 4

For Bootstrap 4 use Sass (SCSS):

// make images responisve by default
img {
  @extend .img-fluid;    
}

answer updated for version 3

Bootstrap 3 has a special class for responsive images (set max-width to 100%). This class is defined as:

.img-responsive {
 display: block;
 height: auto;
 max-width: 100%;
}

Note img tag gets by default:

img {
     vertical-align: middle;
     border: 0;
     page-break-inside: avoid;
     max-width: 100% !important;
     }

So use class="img-responsive" to make your images responsive.

To make all images responsive by default:

css: add the code below under the bootstrap css:

   img {
          display: block;
          height: auto;
          max-width: 100%;
   }

less: add the code below in your mixins.less:

img {
  &:extend(.img-responsive);
}

Note: requires Less 1.4.0. see: https://stackoverflow.com/a/15573240/1596547

Carousel

img tags inside a carousel are responsive by default

Semantic rules

See also the answer of @its-me (https://stackoverflow.com/a/18653778/1596547). Using the above to make all your images responsive by default turns your images to block level elements. Block level elements are not allowed in paragraphs (<p>), see: https://stackoverflow.com/a/4291515/1596547

As far as i understand the distinction of block-level vs. inline elements is replaced with a more complex set of content categories. See also: https://developer.mozilla.org/en-US/docs/Web/HTML/Inline_elemente#Inline_vs._block-level. So in HTML5 a p tag can contain any phrasing element intermixed with normal character data. (see: http://www.w3.org/TR/html-markup/p.html) The img tag is such a phrasing element. The img tag's default value for the display property is indeed inline-block. Changing the display property to block does not violate any of the preceding rules.

Block level elements (display:block) take all the available space of their parent, which seems exactly what you expect for responsive images. So setting display: block; seems a reasonable choice, which has to be preferred above the inline-block declaration.

Images inside p elements which require inline-block as suggest by @its-me (https://stackoverflow.com/a/18653778/1596547) should maybe not be responsive at all.


Excellent suggestion by @BassJobsen, but I'd use display: inline-block; instead of display: block; as that feels more semantic 1 (which means you can be a bit more sure you are not messing up somewhere else).

So, mine would look like this:

img {
  display: inline-block;
  height: auto;
  max-width: 100%;
}

Please do let me know if my understanding is flawed. :)


[1]: For one, images are almost always wrapped in a block-level element if that's the use case; and then again, we also use images in elements like paragraphs (p), where an inline-block would be more appropriate than a block element.