0

i have a div container which is about 600px of width. I'm displaying an image inside this container. I have given the image a width:100% and height:'auto'. There are no issues in this but when i have to display a small image (Ex:width around 50px),because the width is set to 100% it appears blurry. How can i prevent this from happening? My thought was to however getting the width of the image and if it's lower than let's say 80px, the image width is set to a lower value. Is it the correct approach to do this? Or is there any better way?

My code

<div className="home_post_sections">

    <img src={image} className="homepost_image"/>

</div>

css

.home_post_sections {

    width: 610px;
    display: block;
    padding-left: 10px;
    padding-right: 10px;
    padding-top: 10px;
    margin-bottom: 10px;
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
    background-color: white;

}

.homepost_image {

    width: 100%;

}
CraZyDroiD
  • 6,622
  • 30
  • 95
  • 182
  • `width: 100%` would make the image `610px` wide, which would definitely make it blurry. Were you wanting to use `max-width`? – pathurs Jan 23 '18 at 09:32
  • You shouldn't really stretch an image at all, I would be tempted to try `max-width: 100%;` instead, that way smaller images won't stretch and look bad. Of course, if you have *really big images* they probably won't look great shrunk either – musefan Jan 23 '18 at 09:32
  • But i want my div container to fill with the image if it does not affect the resolution much.. I want to set my width to max-width:'100%' only if the image is smaller and will affect the resolution when set to width 100% – CraZyDroiD Jan 23 '18 at 09:36

1 Answers1

1

I want my div container to fill with the image if it does not affect the resolution much.

How much the resolution is affected - how much blur is acceptable - is an opinion. The browser won't make this decision for you.

You can use max-width on the image instead of width. That way the image will never be wider than it's native resolution. So an image with a width of 60px, will take up 60px of the container.

You can also add display: block to the image to remove the small strip of whitespace at the bottom of the container. More info here.

.home_post_sections {
  width: 610px;
  display: block;
  padding-left: 10px;
  padding-right: 10px;
  padding-top: 10px;
  margin-bottom: 10px;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
  background-color: white;
}

.homepost_image {
  max-width: 100%;
  display: block;
}
<div class="home_post_sections">
  <img src="https://unsplash.it/610" class="homepost_image" />
</div>
<div class="home_post_sections">
  <img src="https://unsplash.it/60" class="homepost_image" />
</div>
sol
  • 22,311
  • 6
  • 42
  • 59