【问题标题】:How to center vertically and horizontally text in a div element [duplicate]如何在div元素中垂直和水平居中文本[重复]
【发布时间】:2017-06-12 08:47:43
【问题描述】:

我想将文本置于 div 元素中图像上方的中心。

这是我尝试过的:

CSS:

    .container {
  margin: 0 auto;
  max-width: 1200;
}
.header {
    width: 100%;
}
.ring {
    max-width: 100%;
    position: relative;

}
.flex_text  {
    position: absolute;
    color: #B64547;
    z-index: 100;
    font-family: Poppins;
    font-size: 30px;
    text-align: center;
}


.cell img {
    display: block;
}

HTML:

<div class="container">
    <div class="grid">
        <div class="cell">
            <h4 class="flex_text">Brewing, get started!</h4>
            <img src="img/Kaffe_1.jpg" alt="Ring1" class="ring">
        </div>

显然,它不起作用。该网站是响应式的,因此该解决方案也应该响应式工作。

我环顾四周,尝试了很多不同的方法,但都没有奏效。 我不知道,但也许有 jquery 的解决方案? 谢谢:)

【问题讨论】:

  • 其他问题不需要 jquery 解决方案。
  • // 获取我们的 div var flex_text = $('.flex_text'); var 容器 = $('.container'); // 找到子和父之间宽度差的一半 var left = (container.width() - flex_text.width()) / 2; // 添加父节点的当前左侧位置并设置左侧css值 left += container.offset().left; flex_text.css('left', left); // 对顶部位置做同样的事情 var top = (container.height() - flex_text.height()) / 2;顶部 += 容器.offset().top; flex_text.css('top', toppy);

标签: jquery html css


【解决方案1】:

position: relative;display: inline-block;(或者你可以float它)在父元素上,所以它会在图像周围绘制一个相对定位的正方形,然后top: 50%; transform: translateY(-50%); left: 0; right: 0; 使文本居中。

    .container {
  margin: 0 auto;
  max-width: 1200;
}
.header {
    width: 100%;
}
.ring {
    max-width: 100%;
    position: relative;

}
.cell {
  position: relative;
  display: inline-block;
}
.flex_text  {
    position: absolute;
    color: #B64547;
    z-index: 100;
    font-family: Poppins;
    font-size: 30px;
    text-align: center;
  top: 50%;
  margin: 0;
  left: 0; right: 0;
  transform: translateY(-50%);
}


.cell img {
    display: block;
}
<div class="container">
    <div class="grid">
        <div class="cell">
            <h4 class="flex_text">Brewing, get started!</h4>
            <img src="http://www.jqueryscript.net/images/Simplest-Responsive-jQuery-Image-Lightbox-Plugin-simple-lightbox.jpg" alt="Ring1" class="ring">
        </div>

【讨论】:

  • 谢谢!这工作得很好!我还不明白 transfrom:translateY(-50%) 属性,但是我刚开始接触网页设计,所以我会学习它;)
  • @Janos 太棒了,不客气。将元素向上移动 50% 的高度。
【解决方案2】:

你可以考虑在这里使用 flex。

检查这个sn-p

.grid {
  position: relative;
}
.cell {
  display: flex;
  justify-content: center;
  align-items: center;
}
.flex_text {
  position: absolute;
  color: red;
}
.cell img {}
<div class="container">
  <div class="grid">
    <div class="cell">
      <h4 class="flex_text">Brewing, get started!</h4>
      <img src="http://www.planwallpaper.com/static/images/9-credit-1.jpg" width=200px height=200px alt="Ring1" class="ring">
    </div>
  </div>
</div>

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2014-12-25
    • 2011-05-18
    • 2012-12-16
    • 2013-10-14
    • 2012-03-14
    • 2017-06-28
    • 2012-01-07
    • 2014-09-18
    相关资源
    最近更新 更多