Width: calc() on img is not relative to parent container

我与影子孤独终老i 提交于 2020-01-05 08:24:28

问题


I'm currently working on a layout where I have to use negative margins on the images. The images are inside <div class="entry-content">, which has a padding. To make the images within entry-content go outside the paddings, I use negative margins. To stretch the image outside the <div class="entry-content"> I used width:calc(100%+margin).

This doesn't work as expected though - the 100% seems to be the image's width rather than the width of entry-content. I want the image's width to be relative to entry-content, as the image will be used in a responsive layout.

I'm currently very early in the process, so I still have a fixed width on body.

HTML

<!-- other unrelated code such as header-->
<div class="entry-content">
    <p>
        <img src="http://www.hellothere.se/blog/wp-content/uploads/2014/11/TKD-Promo-title-940x400.jpg" />
    </p>
</div>

CSS

body {
  width: 340px;
}

.entry-content{
  padding: 0 0.75em;
  position: relative;
}

.entry-content img {
  display: block;
  margin: 0 -0.75em;
  width: calc(100%+0.75em);
}

回答1:


MDN calc():

The + and - operators must always be surrounded by whitespace. The operand of calc(50% -8px) for instance will be parsed as a percentage followed by a negative length, an invalid expression, while the operand of calc(50% - 8px) is a percentage followed by a minus sign and a length. Even further, calc(8px + -50%) is treated as a length followed by a plus sign and a negative percentage. The * and / operators do not require whitespace, but adding it for consistency is allowed, and recommended.

The + operator must be surrounded by whitespace.

Therefore it should be width: calc(100% + 0.75em) rather than calc(100%+0.75em)

body {
    width:340px;
}
.entry-content {
    padding: 0 0.75em;
    position:relative;
}
.entry-content img {
    display:block;
    margin: 0 -0.75em;
    width: calc(100% + 0.75em);
}
<div class="entry-content">
    <p>
        <img src="//placehold.it/200" />
    </p>
</div>


来源:https://stackoverflow.com/questions/28488004/width-calc-on-img-is-not-relative-to-parent-container

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!