文字を中央へ表示する方法はいくつか存在しますが、今回は、display: table と、display: table-cell を使い、文字を画面の中央に表示させます。
画面いっぱいに背景画像を表示し、その中央へ文字を表示させます。
こんな感じです。
全画面表示
背景画像を画面いっぱいに表示する方法は以下を参考にして下さい。
文字のセンタリング
文字を画面中央に表示します。
HTML
文字を中央に配置する為のクラスは outクラス と centerクラス になります。
out_imgクラスは画像を表示し、stringクラスは文字の大きさと色を調整しています。
out_imgクラス、stringクラスは今回意識しなくて良く、適宜好きなように変更して下さい。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>test</title> <link href="test.css" rel="stylesheet" type="text/css"> </head> <body> <div class='out out_img'> <div class='center string'>旅に出よう。</div> </div> </body> </html> |
CSS
色々書いてありますが、今回見るところは、outクラス と centerクラスです。
落ち着いて見てみましょう。
outクラス で display: table 、 centerクラス で display: table-cellを指定しています。
display: tableとdisplay: table-cellは要素を親子関係で使用します。
そして、display: table-cell はインライン要素になります。
インライン要素は、vertical-align: middle; により、縦のセンタリングが行えます。
また、text-align: center; は横のセンタリングになります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
body { margin: 0; } .out { display: table; width: 100vw; height: 100vh; } .out_img { background-image: url('1920_1080.png'); background-position: center center; background-repeat: no-repeat; background-size: cover; } .center { display: table-cell; vertical-align: middle; text-align: center; } .string { font-size: 80px; color: #FFFFFF; } |
まとめ
特にありません。