使用position:absolute设置图像大小

时间:2021-07-13 20:28:02

I'm trying to set an image size to its container size + 20px. The container size is relative and will change depending the screen size.

我正在尝试将图像大小设置为其容器大小+ 20px。容器大小是相对的,将根据屏幕大小而变化。

Usually, if I had to resize a div with a background, I'll just set it to position absolute with negatives positions values, but it seems like the img element doesn't follow the same rules. Any solution you know?

通常,如果我必须使用背景调整div的大小,我只需将其设置为绝对位置负值位置值,但似乎img元素不遵循相同的规则。您知道任何解决方案?

HTML:

<div>
  <img />
</div>

Css:

div {
  position: relative;
  overflow: hidden;
  width: 100%;
  padding-top: 56.5%;
}
div img {
  position: absolute;
  top: -20px;
  right: -20px;
  bottom: -20px;
  left: -20px;
}

2 个解决方案

#1


1  

Remember, absolute positioning removes the element from the flow of the document and thus it's container. If you want the image to be relative to the container that it is in, then the position needs to be relative, add the size to it that is needed.

请记住,绝对定位会从文档流中删除元素,从而将其作为容器。如果您希望图像相对于它所在的容器,则该位置需要是相对的,请为其添加所需的大小。

Thinking about this logically, why not actually wrap an extra div around the primary content div and give it some padding?

从逻辑上思考这个问题,为什么不在主要内容div周围包含一个额外的div并给它一些填充?

<div id=container>
  <div id=content>
    some content
  </div>
</div>

Where container has the bg image and padding of 20px.

容器具有bg图像和20px的填充。

#2


0  

Why dont you just use calc function.

为什么不使用calc函数。

width: calc(100% + 20px);

Here is the fiddle http://jsfiddle.net/7hbq5/14/

这是小提琴http://jsfiddle.net/7hbq5/14/

Calc function have a good support http://caniuse.com/#search=calc

Calc函数有很好的支持http://caniuse.com/#search=calc

#1


1  

Remember, absolute positioning removes the element from the flow of the document and thus it's container. If you want the image to be relative to the container that it is in, then the position needs to be relative, add the size to it that is needed.

请记住,绝对定位会从文档流中删除元素,从而将其作为容器。如果您希望图像相对于它所在的容器,则该位置需要是相对的,请为其添加所需的大小。

Thinking about this logically, why not actually wrap an extra div around the primary content div and give it some padding?

从逻辑上思考这个问题,为什么不在主要内容div周围包含一个额外的div并给它一些填充?

<div id=container>
  <div id=content>
    some content
  </div>
</div>

Where container has the bg image and padding of 20px.

容器具有bg图像和20px的填充。

#2


0  

Why dont you just use calc function.

为什么不使用calc函数。

width: calc(100% + 20px);

Here is the fiddle http://jsfiddle.net/7hbq5/14/

这是小提琴http://jsfiddle.net/7hbq5/14/

Calc function have a good support http://caniuse.com/#search=calc

Calc函数有很好的支持http://caniuse.com/#search=calc