你可以使用display:table / table-cell在响应式图像上垂直对齐文本(具有自动高度)吗?

时间:2016-01-06 18:20:10

标签: css

我有一个图像占据折叠,低于固定导航。我想垂直对齐:将#fold-text和V形符号放在图像中间。

html标记:

<div class="row">
  <img class="background-image" src="images/1400px_splash.jpeg">
    <div id="fold-container">
      <div id="fold-text">
        Sign up to learn about upcoming changes!
      </div>
      <div class="fa fa-chevron-down"></div>
    </div>
  </img>
</div>

下面这个CSS通常适用于我想将一个div放在另一个div中,但运气不好(可能是因为img height设置为&#34; auto&#34;?)。谁能告诉我如何纠正这个?

.background-image {
  height: auto;
  width: 100%;
  display: table;
}

#fold-container {
  display: table-cell;
  vertical-align: middle;
}

  #fold-text {
    font-size: 1.6em;
    font-weight: bold;
    background-color: rgba(black, 0.3);
    color: white;
    display: table-cell;
  }

  .fa.fa-chevron-down {
    z-index: 500;
    color:white;
    text-align: center;
    font-size: 2em;
    font-weight: normal;
    display: table-cell;
}

1 个答案:

答案 0 :(得分:0)

您想要的加价:

<div class="row">
  <img class="background-image" src="images/1400px_splash.jpeg">
    <div id="fold-container">
      <div id="fold-text">
        Sign up to learn about upcoming changes!
      </div>
      <div class="fa fa-chevron-down"></div>
    </div>
  </img>
</div>

...是无效的HTML。 <img>标记不包含任何其他标记,因此浏览器看到的内容更像是:

<div class="row">
  <!-- note the self closing img tag -->
  <img class="background-image" src="images/1400px_splash.jpeg"/>
  <div id="fold-container">
    <div id="fold-text">
      Sign up to learn about upcoming changes!
    </div>
    <div class="fa fa-chevron-down"></div>
  </div>
  <!-- </img> don't know what to do with this, because img tags close themselves -->
</div>

你需要做的更像是这样:

<div class="row">
  <div id="fold-container">
    <div id="fold-text">
      Sign up to learn about upcoming changes!
    </div>
    <div class="fa fa-chevron-down"></div>
    <img class="background-image" src="images/1400px_splash.jpeg"/>
  </div>
</div>

...只需确保将适当的样式添加到元素中以正确定位它们。