img标签不尊重父母的右边距

时间:2019-04-18 20:34:45

标签: html css image

我在div中有一张图片。调整窗口大小时,我希望图像与div保持相同的右侧距离。如果我将图像设置为另一个div的背景,则可以正常工作,但无法弄清楚如何使其也用作img标签:

这是它的样子

enter image description here

.mainDiv {
  max-width: 1200px;
  margin: auto;
  width: 95%;
}

.tempImage {
  background: url(https://via.placeholder.com/1200x183);
  height: 183px;
}
<div class="mainDiv">
  <h2>This one works</h2>
  <div class="tempImage"></div>

  <h2>This one doesn't</h2>
  <img src="https://via.placeholder.com/1200x183" alt="">
</div>

3 个答案:

答案 0 :(得分:1)

.mainDiv {
  max-width: 1200px;
  margin: auto;
  width: 95%;
}

.tempImage {
  background: url('https://dummyimage.com/1200x400/000/fff');
  height: 183px;
}

.img-class {
  width: 100%;
}
<div class="mainDiv">
  <h2>This one works</h2>
  <div class="tempImage"></div>

  <h2>This one does now?</h2>
  <img class="img-class" src="https://dummyimage.com/1200x400/000/fff" alt="">
</div>

答案 1 :(得分:0)

尝试使用img标签的max-width属性。

答案 2 :(得分:0)

您可以在图像上设置max-width属性,也可以在容器div上设置溢出属性,具体取决于您是要缩放图像还是将其剪切掉:

最大宽度:

.mainDiv {
  max-width: 1200px;
  margin: auto;
  width: 95%;
}

.tempImage {
  background: url(https://via.placeholder.com/1200x183);
  height: 183px;
}

img {
  max-width: 100%;
}
<div class="mainDiv">
  <h2>This one works</h2>
  <div class="tempImage"></div>

  <h2>So does this one</h2>
  <img src="https://via.placeholder.com/1200x183" alt="">
</div>

溢出:

.mainDiv {
  max-width: 1200px;
  margin: auto;
  width: 95%;
  overflow: hidden;
}

.tempImage {
  background: url(https://via.placeholder.com/1200x183);
  height: 183px;
}
<div class="mainDiv">
  <h2>This one works</h2>
  <div class="tempImage"></div>

  <h2>So does this one</h2>
  <img src="https://via.placeholder.com/1200x183" alt="">
</div>