Div高度为图像高度,图像宽度为div宽度

时间:2023-01-08 21:19:56

I have a div I use as a container and an image I use as a "background" (not literally, I was told I couldn't do this with background attribute) and then a content div:

我有一个div我用作容器和一个图像我用作“背景”(不是字面意思,我被告知我不能用背景属性做这个)然后一个内容div:

CSS

#container {
  display:table;
  width: 100%;
  min-width:100%;
}

.img1 {
  //DON'T KNOW WHAT TO PUT HERE;
}

#content {
  //not important;
}

HTML

<div id="container">
    <img class="img1" src="img.png"/>
    <div id="content"> Content </div>
</div>

I need the container div to be 100% screen width, and so the contained image, while both of them must have the image's resulting height (after the resizing from taking 100% screen width) (no stretching). Any way to do that? I tried a lot of min-height and width combination but nothing worked so far. I prefer CSS and HTML only solutions, if possible.

我需要容器div为100%的屏幕宽度,因此包含的图像,而它们都必须具有图像的最终高度(在调整大小后取100%的屏幕宽度)(无拉伸)。有办法吗?我尝试了很多最小高度和宽度组合但到目前为止没有任何工作。如果可能的话,我更喜欢CSS和HTML解决方案。

2 个解决方案

#1


0  

Not exactly sure what you mean, but how does this look: https://jsfiddle.net/b76fjtcv/

不完全确定你的意思,但这看起来如何:https://jsfiddle.net/b76fjtcv/

basically it's

.img1 {width: 100%;}

This updated version of the fiddle also adds a max width to the img so it doesn't get too fuzzy. Just set the max-width of the .img1 to the image's full width.

这个小提琴的更新版本也为img添加了最大宽度,因此它不会太模糊。只需将.img1的最大宽度设置为图像的全宽。

#2


0  

What are both images? You only have one. look at this, you can use tables for formatting as well if you're not comfortable with div's.

这两个图像是什么?你只有一个。看看这个,你可以使用表格进行格式化,如果你对div不满意的话。

Also, your image could be smaller or larger than the screen width, what then? Do you want scrolling or scaling?

此外,您的图像可能比屏幕宽度更小或更大,那么呢?你想滚动还是缩放?

#1


0  

Not exactly sure what you mean, but how does this look: https://jsfiddle.net/b76fjtcv/

不完全确定你的意思,但这看起来如何:https://jsfiddle.net/b76fjtcv/

basically it's

.img1 {width: 100%;}

This updated version of the fiddle also adds a max width to the img so it doesn't get too fuzzy. Just set the max-width of the .img1 to the image's full width.

这个小提琴的更新版本也为img添加了最大宽度,因此它不会太模糊。只需将.img1的最大宽度设置为图像的全宽。

#2


0  

What are both images? You only have one. look at this, you can use tables for formatting as well if you're not comfortable with div's.

这两个图像是什么?你只有一个。看看这个,你可以使用表格进行格式化,如果你对div不满意的话。

Also, your image could be smaller or larger than the screen width, what then? Do you want scrolling or scaling?

此外,您的图像可能比屏幕宽度更小或更大,那么呢?你想滚动还是缩放?