text-align:center 覚書

text-align:center 覚書:

Home Page上でテキストを指定した高さのセンターに配置したい、というモチベーションで、ちょっと試行錯誤してしまいましたので記録しておきます。非常にStyle初心者の投稿と思っていただければと思います。ブラウザはChromeです。

フォントは以下のように定義をしています。

fontsample.html
<style> 
.fontsample {  
        color: #000000; 
        font-family:sans-serif; 
        font-size: 40pt;  
        line-height : 1.5em} 
</style> 
通常、Style を使って、文字をセンタリングしたいとすると次のように書くでしょう。

example.html
<div style="text-align:center; background-color:#ff0000; class="fontsample">テキスト</div> 
この書き方だと、当たり前ですがページの先頭の真ん中に表示されます。

バックグラウンドに色を付けた理由は、<div>のブロック要素としての範囲を確認したかったからです。



image.png



TOP

高さ方向をtopタグで設定してみます。

example.html
<div style="top:200px; text-align:center; background-color:#00ff00;" class="fontsample">テキスト</div> 
この場合も、テキストの位置はページの先頭になりまる。topタグの設定だけでは高さ方向には動きません。



image.png



position:absolute

高さ方向をtopタグに加えて、position:absolute を設定してみます。

example.html
<div style="position: absolute; top:200px;text-align:center; background-color:#0000ff;" class="fontsample">テキスト</div> 
この設定では、高さ方向は200pxへ移動しましたが、<dev>ブロックのサイズがテキストのサイズに制限されてしまい、テキストはブロックのセンターに配置されているのかもしれませんが、ページの真ん中には表示できませんでした。



image.png



width:100%

widthを100%に設定してみます。

example.html
<div style="position: absolute; top:200px; width:100%; text-align:center; background-color:#ffff00;" class="fontsample">テキスト</div> 
この設定だと、<dev>ブロックの横幅がほぼほぼ真ん中の表示されます。しかし、<dev>ブロックの左マージンと右マージンの幅が異なってしまいました。しかし、今のところこの方法が一番リーズナブルかなと思っています。



image.png



margin: auto

ちなみに<dev>ブロック自体がセンタリングできないか?margin: auto;を設定してみました。

example.html
<div style="position: absolute; top:200px; margin: auto; text-align:center; background-color:#0000ff;" class="fontsample">テキスト</div> 
しかしながら、この方法では<dev>ブロックを移動させることはできませんでした。



image.png



position: relative

何故?今度はpositionをrelativeに変更してみました。

example.html
<div style="position: relative; top:200px; margin: auto; text-align:center; background-color:#ff00ff;" class="fontsample">テキスト</div> 
目的とする場所へ”テキスト”を移動することができました。



image.png



margin: autoを消してみた

relative でうまくいきましたので、margine:auto は不要かもしれない、と消してみました。

example.html
<div style="position: relative; top:200px; text-align:center; background-color:#ff00ff;" class="fontsample">テキスト</div> 
案の定、不要でした。



image.png



ブロックの幅を指定すると

ブロックの幅を指定すると、margin: autoが生きます

example.html
<div style="position: relative; top:200px; width:50%; margin: auto; text-align:center; background-color:#ff00ff;" class="fontsample">テキスト</div> 
</div>ブロックごとセンターへ持っていくことができました。



image.png


多少、使い方が理解できたような気がします。

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2024-02-12 22:08:06 RSSフィード2024-02-12 22:00分まとめ(7件)