CSS
 Computer >> コンピューター >  >> プログラミング >> CSS

CSSのtext-alignプロパティでテキストの配置を設定する方法

CSSでテキストの配置(揃え位置)を設定するには、text-alignプロパティを使用します。このプロパティは、ブロック要素内のインラインコンテンツ(主にテキスト)を左寄せ・右寄せ・中央揃え・両端揃えのいずれかに整列させるために使われます。

text-alignプロパティの値

指定できる主な値は以下のとおりです。

text-align: left | right | center | justify | initial | inherit;
  • left: テキストを左端に揃えます(多くの言語でのデフォルト値)
  • right: テキストを右端に揃えます
  • center: テキストを中央に揃えます
  • justify: 両端を揃え、行間の余白を自動調整します
  • initial: 初期値に戻します
  • inherit: 親要素の設定を継承します

例1:両端揃え(justify)を設定する

以下は、複数カラムのレイアウトに対してtext-align: justify;を適用し、段落の両端をきれいに揃える例です。

<!DOCTYPE html>
<html>
<head>
<style>
.demo {
    -webkit-columns: auto auto; /* Chrome, Safari, Opera */
    -moz-columns: auto auto; /* Firefox */
    columns: auto auto;
    text-align: justify;
}
</style>
</head>
<body>
<h1>Machine Learning</h1>
<div class="demo">
Today's Artificial Intelligence (AI) has far surpassed the hype of blockchain and quantum computing. This is due to the fact that huge computing resources are easily available to the common man. The developers now take advantage of this in creating new Machine Learning models and to re-train the existing models for better performance and results. The easy availability of High Performance Computing (HPC) has resulted in a sudden increased demand for IT professionals having Machine Learning skills.
</div>
</body>
</html>

出力結果

CSSのtext-alignプロパティでテキストの配置を設定する方法

両端揃えを指定することで、テキストの左右が均等に整い、新聞や雑誌のような読みやすいレイアウトになります。

例2:中央揃え(center)を設定する

次に、text-align: center;を使ってテキストを中央に配置する例を見てみましょう。背景にグラデーションを組み合わせることで、視覚的にも分かりやすくなっています。

<!DOCTYPE html>
<html>
<head>
<style>
body {
    background-image: linear-gradient(to right, yellow,orange,yellow,green,blue,indigo,violet);
}
.demo {
    text-decoration: overline;
    text-decoration-color: yellow;
    font-variant: normal;
    text-align: center;
}
</style>
</head>
<body>
<h1>Examination Details</h1>
<p class="demo">Exam on 20th December.</p>
<p class="demo2">Exam begins at 9AM.</p>
</body>
</html>

出力結果

CSSのtext-alignプロパティでテキストの配置を設定する方法

まとめ

text-alignプロパティは、Webページの可読性やデザイン性を高めるための基本かつ重要なCSSプロパティです。justifyは長文の本文に、centerは見出しやキャッチコピーなどに適しており、用途に応じて使い分けることで、より洗練されたレイアウトを実現できます。

  1. CSSのcolorプロパティを使って要素の文字色を設定する方法

    CSSの color プロパティは、要素のテキスト(文字)の色を変更するために使用されます。値には、標準的なカラーネーム、rgb()、rgba()、hsl()、hsla()、そして16進数(HEX)カラーコードなど、さまざまな形式を指定できます。 構文 CSSの color プロパティの基本構文は以下のとおりです。 Selector {     color: /*値*/ } それでは、実際のコード例を見ていきましょう。 コード例1:複数の色指定方法を使う 次の例では、16進数カラーコード、rgba()、hsl() の3つの異なる指定方法を組み合わせて使用

  2. CSSのtext-align&text-justifyプロパティを使ってテキストを揃える方法

    CSSのtext-justifyプロパティは、要素に適用される均等割り付け(ジャスティフィケーション)の方式を指定するために使用します。一方、text-alignプロパティは、要素内のテキストの水平方向の配置(左寄せ・中央揃え・右寄せ・両端揃えなど)を設定します。 なお、text-justifyプロパティは、text-align: justify;が指定されている場合にのみ有効になります。 text-justifyプロパティの主な値 auto:ブラウザが自動的に適切な均等割り付け方法を選択します(初期値)。 none:均等割り付けを無効にします。 inter-word:単語と単語の間隔を調整