我如何将一个div垂直居中在一个div中,这个div的高度因其内部的img而变化?

时间:2016-12-14 15:33:24

标签: html css

我有这个未完成的示例代码块:

<div style="position: relative; width: 100%; float:left;">
  <img style="max-width:1920px; width:100%; display:block;position:relative; float: left;">
  <div width:400px; ><p>Text and more Text<p></div>
</div>

我希望文本div始终位于图片/父div的垂直中间,并且它的margin-right类似10%;,因为图片高度会因窗口大小而变化希望文本框始终位于图像的垂直中间。

2 个答案:

答案 0 :(得分:0)

使用 CSS定位,并应用position: absolute

请看下面的代码段:

.box-holder {
  position: relative;
  display: inline-block;
}

p {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  margin: 0;
  text-align: center;
  background: rgba(255, 255, 255, 0.5);
}
<div class="box-holder">
  <img src="http://placehold.it/200x200" />
  <p>Text and more Text</p>
</div>

希望这有帮助!

答案 1 :(得分:0)

您可以使用position执行此操作。

img {
  width: 100%;
}

.wrapper {
  position: relative;
}

p {
  background: rgba(0, 0, 0, 0.3);
  padding: 20px 0;
  text-align: center;
  color: #eee;
  text-transform: capitalize;
  font-family: sans-serif;
  font-style: 18px;
}

.pictureCaption {
  position: absolute;
  display: block;
  width: 100%;
  top: calc(50% - 38px);
}
<div class="wrapper">
  <img src="https://images.unsplash.com/photo-1462834026679-7c03bf571a67?dpr=1&auto=compress,format&fit=crop&w=1199&h=791&q=80&cs=tinysrgb&crop=">
  <p class="pictureCaption">This is some text about this picture.</p>
</div>