为什么我的图片宽度不能继承父级div的宽度?

14

各位,我有一个像这样的 div:

<div id="image-container">
 <img id="image" src="#" > //with an image inside
</div>

这样进行样式设置:

#image-container {
    width: 750px;
    height: 360px !important;
    text-align: center;
}

但是当我加载页面并检查图像以了解其尺寸时,它显示:

element.style {
    height: 600px;
    width: 600px;
}

为什么图像没有继承div的宽度?由于某些原因,我无法手动设置所需的图像宽度,因此我不能这样做:
#image {
 width : 330px; //manually putting width
 height: 303px; //same same which i cannot do this for some reason
}

你有任何想法为什么会出现这种情况,或有解决方法吗?

我尝试了以下解决方案:

查看元素后,我得到了以下内容:

#image {
    height: inherit; // crossed-out
    width: inherit; // crossed-out
}

有东西正在覆盖我的图像尺寸。

5个回答

9
请尝试使用这个代码示例
#image-container {
    width: 750px;
    height: 360px !important;
    text-align: center;
    overflow: hidden;
}

#image-container img{ 
    width: inherit;
}

6

4
你应该将图片的widthheight属性设置为100%inherit或相同的值,以便完全填充父元素的空间。
#Container {
    width: 200px;
    height: 200px;
}

#Image {
    width: inherit;
    height: inherit;
}

您可以在此处的fiddle中进行检查。同时,请确保文档中没有加载其他CSS。


3
(如果我忘记了怎么做)
我正在使用Bootstrap 3,有一个宽度为768px的列。我的标记如下:
<div class="col-lg-8">
    <img src="path/to/image.png" />
</div>

将宽度设置为100%会导致其他图像(特别是那些宽度较小的图像)变得模糊。因此,我的解决方案是使用max-width属性:

// parent div's width is currently 768px.
img { max-width: 100% }

所以其他图片(宽度较小)将使用它们的确切宽度。

0
#image {
    width: 100%;
    height: 100%;
}

足矣


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接