Improving the images

:  ~ 1 min read

I have on site several kinds of images, but since I write my posts in Markdown, and I want to make use of its native features, the images created this way have no class. So I had to find a way to style these imgs.

First step, CSS:

img {
  border-radius: 2px;
  -webkit-box-shadow: #777 0 0 3px 1px;
  -moz-box-shadow: #444 0 0 3px 1px; /* color, h-offset, v-offset, blur, spread */
  box-shadow: #777 0 0 7px 0; /* inset is optional */
  
  // This will center the images inside posts.
  &:not([class]) {
    margin: 0 auto;
    display: table;
  }
}

But the problem here is with images that are wider than the article's width. Second step, jQuery:

$('img:not([class])').on('load',function() {
  if (img.width() > $('section').width()) {
    img.wrap("<div class='centered-image-wrapper'></div>");
  }
});

Where centered-image-wrapper has the same border, border-radius, and shadow as img, with overflow: hidden; and text-align: center; added. But now, on resize the images will remain unwrapped, since the condition was made on load. Step three:

$(document).ready(function() {
  $(window).resize(function() {
    resizeImage($('img:not([class])'))
  });
  
  $('img:not([class])').on('load',function() {
    resizeImage($(this))
  });
});

var resizeImage = function(img) {
  if (img.width() > $('section').width()) {
    if (!img.closest('.centered-image-wrapper').length) {
      img.wrap("<div class='centered-image-wrapper'></div>");
    }
  }
  else if (img.closest('.centered-image-wrapper').length) {
    img.unwrap()
  }
};