我有一个图像 (508 x 564),我想将其完全放入其父容器中。
即使使用 width: 100%
或 max-width: 100%
,这也是图像拉伸(stretch)到的最大宽度。我正在使用分屏样式,仅显示分屏的左侧(因此,您将在 CSS 中看到 width: 50%
。)
HTML:
<div class="mainContainer">
<div class="imageContainer">
<img class="image" src="path/to/image"></img>
</div>
<div class="textContainer">
<h1>Some text here</h1>
</div>
</div>
CSS:
.imageContainer {
width: 50%;
}
.image {
width: 100%;
height: 100%;
background-size: cover;
}
如果我指定 width: 100%
,图像理想情况下应该放大以适合父容器,对吧?我也尝试过 max-width: 100% ,结果相同。
注意:我忘了提及我正在使用 .SVG 文件。这可能就是为什么它的行为不像我期望的那样喜欢 JPG/PNG 文件!!!!
最佳答案
-编辑 SVG-
您可以使用 <object>
显示 svg 图像, <embed>
, <iframe>
或<svg>
如下:
使用<object>
标签:
<object type="image/svg+xml" data="image.svg">
Update your browser to support support SVG <-- displayed if svg is not supported
</object>
使用<embed>
标签:
<embed type="image/svg+xml" src="image.svg" />
使用<iframe>
标签:
<iframe src="image.svg"></iframe>
使用<svg>
标签:
<svg xmlns="http://www.w3.org/2000/svg"></svg>
对于上一个未经编辑的问题:
-对于 JPEG/PNG-
你的 html 和 css 标记都搞乱了。您需要:
- 关闭 div 标签
- 正确关闭img标签
- 用分号结束 CSS 属性
像这样:
HTML:
<div class="mainContainer">
<div class="imageContainer">
<img class="image" src="//i.ytimg.com/vi/tntOCGkgt98/maxresdefault.jpg" />
</div>
<div class="textContainer">
<h1>Some text here</h1>
</div>
</div>
CSS:
.imageContainer {
width: 50%;
}
.image {
width: 100%;
height: 100%;
background-size: cover; <!-- remove this. Only applicable to background images and not inline images -->
}
jsFiddle:https://jsfiddle.net/e0d8my79/192/ <-- 50% 宽度
jsFiddle:https://jsfiddle.net/e0d8my79/194/ <-- 100% 宽度
关于html - SVG 图像的大小无法适应父容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42030678/