用vp设置img的高度时,它会影响同级元素的宽度,而使用%时,它不会影响同元素的宽度,为什么?

时间:2018-07-15 16:15:11

标签: css responsive-design

因此,如果我用vp在img上设置了高度道具,则h2(同级元素)相对于img宽度(因此就是我想要的)有换行符。但是,如果我将图像高度设置为%,则h2将占用所需的宽度。

除了设置相对于浏览器的图像大小以外,vp确实在做什么。

HTML

<div class="container">
  <div class="single-container">
    <img src="https://imagesvc.timeincapp.com/v3/mm/image?url=https%3A%2F%2Ftimedotcom.files.wordpress.com%2F2014%2F11%2F84146440.jpg&w=800&q=85" alt="">
    <h2>I'm trying to not make this more than image width.</h2>
  </div>
    <div class="single-container">
    <img src="https://imagesvc.timeincapp.com/v3/mm/image?url=https%3A%2F%2Ftimedotcom.files.wordpress.com%2F2014%2F11%2F84146440.jpg&w=800&q=85" alt="">
    <h2>I'm trying to not make this more than image width.</h2>
  </div>
    <div class="single-container">
    <img src="https://imagesvc.timeincapp.com/v3/mm/image?url=https%3A%2F%2Ftimedotcom.files.wordpress.com%2F2014%2F11%2F84146440.jpg&w=800&q=85" alt="">
    <h2>I'm trying to not make this more than image width.</h2>
  </div>
</div>

CSS

.container {
  display: flex;
}

img {
  height: 30vh;
}

JSFiddle链接

https://jsfiddle.net/bqdxze94/9/

1 个答案:

答案 0 :(得分:0)

也许这样可以工作:

解决方案: display: table; width: 0;

注意:我在每个项目周围添加了一些空间,并放大了第二张图片以显示行为

View StackBlitz :D

.container {
  display: flex;
  justify-content: space-around;
}

img {
  height: 30vh;
}

.img2 {
  height: 60vh;
}

.single-container {
  display: table;
  width: 0;
}
<div class="container">
  <div class="single-container">
    <img src="https://imagesvc.timeincapp.com/v3/mm/image?url=https%3A%2F%2Ftimedotcom.files.wordpress.com%2F2014%2F11%2F84146440.jpg&w=800&q=85" alt="">
    <h2>I'm trying to not make this more than image width.</h2>
  </div>
    <div class="single-container">
    <img class="img2" src="https://imagesvc.timeincapp.com/v3/mm/image?url=https%3A%2F%2Ftimedotcom.files.wordpress.com%2F2014%2F11%2F84146440.jpg&w=800&q=85" alt="">
    <h2>I'm trying to not make this more than image width.</h2>
  </div>
    <div class="single-container">
    <img src="https://imagesvc.timeincapp.com/v3/mm/image?url=https%3A%2F%2Ftimedotcom.files.wordpress.com%2F2014%2F11%2F84146440.jpg&w=800&q=85" alt="">
    <h2>I'm trying to not make this more than image width.</h2>
  </div>
</div>