在 flexbox 中将文本居中放置在图像上

新手上路,请多包涵

我如何将文本居中对齐 <img> 最好使用 FlexBox?

 body {
  margin: 0px;
}

.height-100vh {
  height: 100vh;
}

.center-aligned {
  display: box;
  display: flex;
  box-align: center;
  align-items: center;
  box-pack: center;
  justify-content: center;
}

.background-image {
  position: relative;
}

.text {
  position: absolute;
}
 <section class="height-100vh center-aligned">
  <img class="background-image" src="http://vignette2.wikia.nocookie.net/uncyclopedia/images/f/f8/Stand-out-in-the-crowd-300x300.jpg" />
  <div class="text">SOME TEXT</div>
</section>

原文由 allegutta 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 253
2 个回答

要使文本在图像上居中,您不需要 flexbox。只需使用 CSS 定位属性。

 .height-100vh {
    height: 100vh;
    position: relative;               /* establish nearest positioned ancestor for
                                         absolute positioning */
}

.text {
    position: absolute;
    left: 50%;                        /* horizontal alignment */
    top: 50%;                         /* vertical alignment */
    transform: translate(-50%, -50%); /* precise centering; see link below */
}

 body {
  margin: 0px;
}

.height-100vh {
  height: 100vh;
  display: flex;           /* establish flex container */
  flex-direction: column;  /* stack flex items vertically */
  position: relative;      /* establish nearest positioned ancenstor for absolute positioning */
}

.text {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-weight: bold;
}

.center-aligned {
  display: flex;
  align-items: center;
  justify-content: center;
}
 <section class="height-100vh center-aligned">
  <img class="background-image" src="http://vignette2.wikia.nocookie.net/uncyclopedia/images/f/f8/Stand-out-in-the-crowd-300x300.jpg/revision/latest?cb=20090904155448" />
  <div class="text">SOME TEXT</div>
</section>

修改后的代码笔

上面的代码将文本在图像上垂直和水平居中:

在此处输入图像描述

有关居中方法的更详细说明,请参见:

原文由 Michael Benjamin 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以只用 relative 定位 inline-block <div> 包裹图像,并以这种方式提供文本:

 * {margin: 0; padding: 0; list-style: none;}
.img-holder {position: relative; display: inline-block;}
.img-holder img {display: block;}
.img-holder p {position: absolute; top: 50%; left: 0; right: 0; transform: translate(0, -50%); text-align: center; color: #fff; text-shadow: 0 0 15px;}
 <div class="img-holder">
  <img src="http://bit.ly/1YrRsis" alt="">
  <p>Text Aligned Centrally Vertical &amp; Horizontal.</p>
</div>

现在 <div> 是一个 inline 可以设置样式的元素。

预习:

原文由 Praveen Kumar Purushothaman 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题