将 div 直接放置在高度未知的图像下方,位置为绝对/相对

我有一个占视口宽度 88% 的图像,因此它的高度是动态的。我需要将我的 .pricecontainermobile div 直接放置在图像下方,这样无论视口如何,它都会直接位于图像下方...我尝试通过位置:绝对/相对进行设置,但我无法让它工作,因为我需要我的图像垂直居中(负46px)...我相信这扰乱了绝对/相对...我哪里出错了?

注意这仅适用于纵向...请查看此方向的代码以查看正确的样式等。

JSFiddle: https: //jsfiddle.net/cz9hebg7/1/

代码:

<div id="placement">

      <img src="images/" alt="."/>

      <div class="pricecontainermobile">

        <h1>TEST</h1>

        <h2>$ 30.00</h2>

      </div>

    </div>




.pricecontainermobile>h2 {

  text-align: center;

  font-size: 12px;

}


.pricecontainermobile>h1 {

  display: block;

  font-family: neue-haas-grotesk-text, sans-serif;

  color: white;

  font-weight: 500;

  font-style: normal;

  list-style: none;

  text-align: center;

  text-decoration: none;

  font-size: 13px;

  top: 0;

}


.pricecontainermobile {

  display: block;

  width: 100%;

  background: blue;

  position: absolute;

}

#placement {

    display: block;

    position: fixed;

    left: 0;

    right: 0;

    top: 0;

    bottom: 0;

    height: 100%;

    width: 88%;

    margin-left: 6%;

    background: red;

}

#placement img {        

    width: 100%;

    height: auto;

    position: relative;

    top: calc(50% - 46px);

    transform: translateY(-50%); 

}


手掌心
浏览 102回答 1
1回答

MMTTMM

如果 .pricecontainermobile 块的高度是固定的,您可以将其与 img 一起放入容器中,然后将容器放置在 #placement 中,而不是 img 中。所以我将h1和h2的高度固定为18px;如果你愿意的话你可以改变它。另请注意,我为 img 使用了占位符图像。.pricecontainermobile>h2 {&nbsp; text-align: center;&nbsp; font-size: 12px;&nbsp; line-height: 24px; /* new: fix height */&nbsp; margin: 0;}.pricecontainermobile>h1 {&nbsp; font-family: 'neue-haas-grotesk-text', sans-serif;&nbsp; color: white;&nbsp; font-weight: 500;&nbsp; font-style: normal;&nbsp; list-style: none;&nbsp; text-align: center;&nbsp; text-decoration: none;&nbsp; font-size: 13px;&nbsp; line-height: 24px; /* new: fix height */&nbsp; margin: 0;}.pricecontainermobile {&nbsp; display: block;&nbsp; width: 100%;&nbsp; background: blue;&nbsp; position: absolute;&nbsp; padding: 6px 0; /* new: correct header's margins */}#placement {&nbsp; display: block;&nbsp; position: fixed;&nbsp; left: 0;&nbsp; right: 0;&nbsp; top: 0;&nbsp; bottom: 0;&nbsp; height: 100%;&nbsp; width: 88%;&nbsp; margin-left: 6%;&nbsp; background: red;}#placement .imgcontainer { /* new: moved from img */&nbsp; position: relative;&nbsp; top: calc(50% - 30px); /* corrected for height of header */&nbsp; transform: translateY(-50%);}#placement img {&nbsp; vertical-align:top;&nbsp; width: 100%;&nbsp; height: auto;}<div id="placement">&nbsp; <div class="imgcontainer">&nbsp; &nbsp; <img src="https://placehold.it/600x200" alt="." />&nbsp; &nbsp; <div class="pricecontainermobile">&nbsp; &nbsp; &nbsp; <h1>TEST</h1>&nbsp; &nbsp; &nbsp; <h2>$ 30.00</h2>&nbsp; &nbsp; </div>&nbsp; </div></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5