Set "min-width:100%" for images larger than 400px? JS or CSS

Viewed 160

I am trying to set up a JS/jQuery/CSS solution to select images larger than 400px and set them to be the full width of the container (min-width: 100%).

However, it should not apply to images smaller than 400px to avoid selecting really small ones or thumbnails. Normally, I'd just use classes, but the markup is generated by an old wiki intranet system which doesn't give users the ability to set classes.

Any help would be appreciated.

.container {
  width: 700px;
  border: solid 1px red;
}

.container img {
  border: solid 1px green;
  max-width: 100%;
  height: auto;
  display: block;
  margin: auto auto;
}
<div class="container">
  <img src="https://via.placeholder.com/140x100" />
  <img src="https://via.placeholder.com/500x100?text=Should_be_full_width" />
</div>

3 Answers

You can use the naturalWidth property after the images are loaded (use the window load event) and manually add a class (use classList).

window.addEventListener('load', () => {
  const images = document.querySelectorAll('img');
  for (let image of images) {
    if (image.naturalWidth >= 400) {
      image.classList.add('full-width');
      // or set the style directly if you have to
      // image.style.minWidth = '100%';
    }
  }
});
.container {
  width: 700px;
  border: solid 1px red;
}

.container img {
  border: solid 1px green;
  max-width: 100%;
  height: auto;
  display: block;
  margin: auto auto;
}

.full-width {
  min-width: 100%;
}
<div class="container">
  <img src="https://via.placeholder.com/140x100" />
  <img src="https://via.placeholder.com/500x100?text=Should_be_full_width" />
</div>

This would work

var images = $("img")

for (let i = 0; i < images.length; i++) {
    if (images[i].width >= 400) {
    images[i].style.minWidth = "100%";
  }
}

$(function() {
  $('img').each((i, img) => {
    let width = parseInt($(img).css('width'));
    if (width > 400) {
      $(img).css('width', '100%');
    }
  });
});
.container {
  width: 700px;
  border: solid 1px red;
}

.container img {
  border: solid 1px green;
  max-width: 100%;
  height: auto;
  display: block;
  margin: auto auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <img src="https://via.placeholder.com/140x100" />
  <img src="https://via.placeholder.com/500x100?text=Should_be_full_width" />
</div>

Related