将图像的宽度设置为其父级的父级的父级

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

我试图将此示例图片的宽度设置为紫色背景“#container”div 宽度的 100%,即使页面已重新调整大小。由于其他原因,它以这种方式构建,我认为我无法绕过。看起来应该是一个简单的解决方案,但我似乎找不到答案。

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>

CSS:

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

li {
    list-style: none;
}

.gallery li img {
    width: 100%;
}

要使width: 100%生效,必须预先定义父元素的宽度。您的 <li> 元素很可能不是这种情况。

我认为您的实际问题是 <ul> 元素上的填充阻止了您的图像占据整个宽度。尝试向其中添加 padding-left:0;

您需要清除 ul 的默认边距和填充,方法是将其设置为 0,并将图像宽度更改为 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%;
}