将文本中心放在flexbox中的图像上 [英] Center text over an image in flexbox

查看:191
本文介绍了将文本中心放在flexbox中的图像上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用FlexBox将文本中心对齐到< img>

How can I centre align text over an <img> preferably using 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>

推荐答案

布局可以通过flexbox和定位属性来实现。没有对HTML的更改。

The layout can be achieved with flexbox and positioning properties. No changes to HTML.

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

.text {
    position: absolute;  
    left: 50%;                        /* horizontal alignment */
    top: 50%;                         /* vertical alignment */
    transform: translate(-50%, -50%); /* horizontal, vertical alignment fine tuning;
                                        explanation: http://stackoverflow.com/q/36817249 */
 }

修订的Codepen

上面的代码将文本的垂直和水平方向置于图片的中心:

The code above centers the text both vertically and horizontally over the image:

< a>

这篇关于将文本中心放在flexbox中的图像上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆