Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8766

要素を中央に持っていくまとめ(HTML,CSS)

$
0
0
要素を中央に持ってくるやり方を毎回忘れるのでまとめてみました。 他にもやり方があるかもしれませんので、気づいた方おりましたら コメント頂けますと幸いです。 ①文字列の高さを中央にする index.html <style> .container { height: 100px; position: relative; box-sizing: border-box; border: 5px solid #76d3f4; box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.25); margin: 20px 0px; } .char_heigth-center { /*文字要素の高さを整える*/ line-height: 100px; } </style> <div class="container"> <p class="char_heigth-center">文字の高さを中央に</p> </div> 結果 ②文字の横幅を中央にする text-align:center;でも可能だが、改行して複数行になると 両方中央寄せになるのうで使い分けが必要 index.html <style> .container { ・・・ } .char_width-center { display: flex; justify-content: center; } </style> <div class="container"> <p class="char_width-center">文字の横の配置を中央に</p> </div> 結果 ③連続した文字要素を中央に配置(縦と横を中央に) index.html <style> .container { ・・・ } .char_heigth-center { line-height: 100px; } .char_width-center { display: flex; justify-content: center; } .disflex { display: flex; } .items { margin-right: 10px; } </style> <div class="container"> <div class="disflex char_heigth-center char_width-center"> <p class="items">文字列1</p> <p class="items">文字列2</p> <p class="items">文字列3</p> </div> </div> 結果 ④文字列以外の配置を中央にする 画像のように中の文字列は中央に配置されないので注意 index.html <style> .container { ・・・ } .element-center { width: 60%; height: 60%; margin: auto; position: absolute; top: 0; bottom: 0; left: 0; right: 0; border: 5px solid #ff0000; box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.25); } </style> <div class="container"> <div class="element-center">テスト</div> </div> 追記:以下の構文でも可能みたいです。 .element-center { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }   または親要素に .element-align { display: flex; justify-content: center; align-items: center; }  ※position は要素ごとにを中央配置できるが、   flexは親要素の中身全てが中央配置になるため、使い分けは必要です。 追記2:右下に配置する場合は以下のようにする .element-right-bottom{ position: absolute; right: 0; bottom: 0; } 結果

Viewing all articles
Browse latest Browse all 8766

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>