通过CSS实现图像上方的文本水平居中

26
请提供原文。
<div class="image">
    <img src="sample.png"/>
    <div class="text">
       Text of variable length
    </div>
</div>

何时使用:

.image {
    position:relative;
    text-align:center; // doesn't work as desired :(
}

.text {
    position:absolute;
    top:30px;
}

请问,有没有办法将位于 .image div 中的文本水平居中对齐?我不能使用 left 属性,因为文本长度未知,而 text-align 属性无法作用于 .text div :(

谢谢。

5个回答

67

尝试以下 CSS:

.image {
    position:relative;
}

.text {
    left: 0;
    position:absolute;
    text-align:center;
    top: 30px;
    width: 100%
}

这只是@MyHeadHurts链接的一个变体,希望能给你提供一些可以做的想法。 - user5306470
可以使用以下示例进行操作: http://jsbin.com/docoma/1/edit?html,css,output - GabLeRoux

13

试一试:

.image {
    position:relative;
}

.text {
    position: absolute;
    top: 0;
    left: 0;
    width:100%;    
    height:100%;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
}

如果您使用flex,为什么不使用“order”交换顺序,而不是使用绝对定位的hack呢? - Pete

2

首先需要对 .image 元素进行浮动,以便将其块级子元素“折叠”到元素的宽度,并在 .text 元素上使用 text-align

.image {
    float: left;
}
.text {
    text-align: center;
}

JS Fiddle演示

或者您可以简单地给它一个display: inline-block,这将允许它包含块级内容,并保持在文档流中:

.image {
    display: inline-block;
}
.text {
    text-align: center;
}

JS Fiddle demo.


1

你可不可以使用background-image: url('/yourUrl/');将图片作为“image” div 的背景图片,然后不要把文本放在自己的div中,而是把它放在图片div中,然后应用text-align: center;


0

使用Flex是一种更加“灵活”的选择 :-)

#countdown {
  font-size: 100px;
  z-index: 10;
}

#countdown-div {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

#bg-image {
  width: 100vw;
  height: 100vh;
  position: absolute;
  top: 0px;
  left: 0px;
}

<div>
  <div id="countdown-div">
    <h1 id="countdown">10</h1>
  </div>
  <img id="bg-image" src="https://lh3.googleusercontent.com/proxy/PKaxc9qp52MkavbkMnnbu0AZAGcqxJCoa7wIgtCmOr2e1x9ngdsteITX6x4JqDDFOhhdZmF79Ac5yevMGaUmcSaFnFYsHQtLPxHg56X_8PfP1fNkxMNXYd3EzhuCb3eJ2qQA">

</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接