Brad
Brad

Reputation: 59

Setting the width of an image to its parent's parent's parent

I'm trying to make the width of this sample image to be 100% of the width of the purple background "#container" div, even as the page is re-sized. It's structured this way for other reasons, that I don't think I can get around. It seems like it should be a simple solution, but I cant seem to find an answer.

The HTML:

<html>
    <head>
        <title>Sample Title</title>
        <link rel="stylesheet" type="text/css" href="style.css"/>
        <meta name="viewport" content="width=device-width">
    </head>
    <body>
        <div id="container">
            <div class="media">
                <ul class="gallery" id="house1">
                    <li><img src="https://analogphotogs.files.wordpress.com/2011/05/lc-w_sample_01.jpg"></li>
                </div>
            </div>
        </div>
    </body>
</html>

The CSS:

#container {
    width: 50vw;
    height: 50vw;
    background-color: purple;
}

li {
    list-style: none;
}

.gallery li img {
    width: 100%;
}

Upvotes: 1

Views: 111

Answers (2)

Thijs Riezebeek
Thijs Riezebeek

Reputation: 1812

For the width: 100% to take effect, the width of the parent element has to defined beforehand. This is most likely not the case for your <li> element.

I believe your actual problem is that the padding on the <ul> element is preventing your image from taking up the entire width. Try adding padding-left:0; to it.

Upvotes: 1

gazelle
gazelle

Reputation: 135

You need to clear ul's default margin and padding by setting it to 0, and changing the image width to max-width: 100%.

#container {
  width: 50vw;
  height: 50vw;
  background-color: purple;
}

ul{
  padding:0;
  margin:0;
}

li {
  list-style: none;
}

.gallery li img {
  max-width: 100%;
}

Upvotes: 1

Related Questions