フレックスボックスでテキストを画像の上に中央揃えにする 質問する

フレックスボックスでテキストを画像の上に中央揃えにする 質問する

できれば FlexBox を使用してテキストを中央揃えにするにはどうすればよいでしょうか<img>?

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>

ベストアンサー1

テキストを画像の中央に配置するには、フレックスボックスは必要ありません。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>

改訂版コードペン

上記のコードは、テキストを画像上で垂直方向と水平方向の両方の中央に配置します。

ここに画像の説明を入力してください

センタリング方法の詳細な説明については、以下を参照してください。

おすすめ記事