HTML CSS文字 縦中央揃え

初めはこうだった PCサイトだといいけど、スマホだと駄目 f:id:happy_teeth_ago:20191003221720p:plain

スマホ版 駄目だこりゃ

f:id:happy_teeth_ago:20191003221815p:plain

ソース

   <div class="bg-slider">
    <div class="bg-slider_title ">
      <h1>BAI PO</h1>
      <p class="lead">Thai massage</p>
    </div>
  </div>

CSS

bg-slider {
    width: 100vw;
    height: 100vh;
    background-position: center center;
    background-size: cover;
     display: flex;
    align-items: center;
    /* 中央よせ */
    justify-content: center;
    position: relative;
}

.bg-slider__title {
    position: absolute;
    height: 100%;
    top:50%;
    left: 35%;
    font-family: 'Noto Serif', serif;
    color: #fff;
    font-size: 6.5rem;
    line-height: 1.5;
    font-weight: bold;
    text-align: center;
    text-shadow: 1px 1px 10px #000;
}

CSSを修正

.bg-slider {
    width: 100vw;
    height: 100vh;
    display: table;
    background-position: center center;
    background-size: cover;
    align-items: center;
    /* 中央よせ */
    justify-content: center;
    position: relative;
}

.bg-slider_title {
    position: absolute;
    top: 35vh;
    display: table-cell;
    vertical-align: middle;
    width: 100vw;
    height: 50vh;
    font-family: 'Noto Serif', serif;
    color: #fff;
    font-size: 6.5rem;
    line-height: 1.5;
    font-weight: bold;
    text-align: center;
    text-shadow: 1px 1px 10px #000;
    display: table-cell;
}

文字の位置を決めるのだから

親要素に

position: relative;

//point
display: table

子要素に 

 position: absolute;
    top: 35vh;
//point
    display: table-cell;

を利用する

「display」プロパティの"table"や"table-cell"を使うとtableタグを使ったかのような表組みレイアウトが利用できる レスポンシブでも利用できるので重宝する。

tableはもう使うことは無いと思っていたけど これなら大丈夫!

displayで生き残っていたのだね

f:id:happy_teeth_ago:20191003222348p:plain

参考にさせていただきました

https://www.granfairs.com/blog/staff/centering-by-css