tcaissie
tcaissie

Reputation: 83

How do I make an <img> fill the entirety of a <div> that's set to width: 100%;

StackOverflow community.

I want an image to fill the entirety of a box that's 100% width and 450px height.

<div class="homepics">
  <img src="./homepic.jpg" alt="Home Picture" />
</div>

.homepics {
    width: 100%;
    height: 450px;
}

I did my best to find an answer, but in the examples I've seen the box always has a determined width and height, which does not apply to my case. Or maybe it can if I knew how to make the box take 100% of the width of the viewer's browser without having to use the 100% value on the width attribute.

So, if I want the homepic.jpg to fit my .homepics div, how do I proceed?

I'd appreciate any help on this.

Upvotes: 0

Views: 180

Answers (2)

Clayton Engle
Clayton Engle

Reputation: 581

Here's a few methods:

1) Set the image as a background-image, and then the size as cover, to cover the whole of the div:

.homepics {
    width: 100%;
    height: 450px;
    background-image: url(your-jpg.jpg);
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
}

2) if you want the whole of the image to show, no matter the container, try contain:

.homepics {
    width: 100%;
    height: 450px;
    background-image: url(your-jpg.jpg);
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;
}

3) if you are okay with the image becoming distorted, you can set it's width and height to 100% and let it fill the area:

<img src="..." width="100%" height="450">

4) if you are okay with space on either side, then you are essentially using bootstrap's `.img-responsive' class, which is like this:

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

This will stop at the actual width of the image. If you want it to blow out past that, try this (it may become blurry on large monitors):

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

One of these options should work. If not, let me know.

Upvotes: 0

jeh
jeh

Reputation: 577

You can use it as a background image so that the container can adjust to screen size. Unfortunately it does crop off parts of the image if it has a drastically different size ratio.

The image used in the example below is 350x150 but it stretched to fill the container that is 450px tall.

Please note, the smaller the image in comparison to the container the more fuzzy it will appear. For 100% screen width backgrounds you'll want a high definition image around 1440px to 1920px wide.

.bg-container{
  width:100%;
  height:450px;
  background-image:url('http://via.placeholder.com/350x150');
  background-position:center;
  background-repeat:no-repeat;
  background-size:cover;
}
<div class="bg-container">
</div><!-- bg-container -->

Upvotes: 2

Related Questions