CSSを使って1行のテキストで均等割付・両端揃えを実現する方法

CSSを使って1行のテキストで均等割付・両端揃えを実現する方法

CSSを使って1行のテキストで均等割付・両端揃えを実現する方法

1行のテキストで均等割付・両端揃えを実装する方法をご紹介いたします。CSSのみで実現でき、表などで活用できるので覚えておくと便利かと思います。

スポンサードリンク

CSSを使って1行のテキストで均等割付・両端揃えを実現する方法

以下のような表を作成することを前提として説明いたします。

表の均等割付・両端揃え

Safari非対応の均等割付・両端揃えの実装方法

まずは、Safariには非対応ですが、最も簡単な均等割付・両端揃えの実装方法です。

HTMLは以下の通りで、シンプルな表ですね。

<table>
  <tr>
    <th>均等割付</th>
    <td>CSSで均等割付</td>
  </tr>
  <tr>
    <th>均等</th>
    <td>CSSで均等割付</td>
  </tr>
  <tr>
    <th>割付</th>
    <td>CSSで均等割付</td>
  </tr>
</table>

CSSでは以下のように指定します。

table {
  width: 40%;
  border-collapse: collapse;
}

th,
td {
  padding: 10px 20px;
  color: #333;
  border: solid 1px #aaa;
}

th {
  background: #eaf6ff;
  font-weight: bold;
  font-size: 16px;
  width: 120px;
  text-align: justify;
  text-align-last: justify;
  text-justify: inter-ideograph;
}

td {
  font-size: 14px;
}

重要な点はthの部分です。

th {
  text-align: justify;
  text-align-last: justify;
  text-justify: inter-ideograph;
}

「text-align-last: justify;」で最終行を両端揃えにすることで、1行のテキストの均等割付を実現しています。

ただ、ChromeやFirefoxだけなら「text-align-last: justify;」だけで良いのですが、IEやEdgeではtext-align-lastが効きません。そこで「text-align: justify;」と「text-justify: inter-ideograph;」を追加して、IEやEdgeに対応しています。

これで、Safari以外の主要ブラウザはカバーできます。

主要ブラウザすべてに対応した均等割付・両端揃えの実装方法

Safariにも対応したいという場合は、少々面倒ですが下記の方法で実現可能です。

まずHTML側では、以下のように1文字ずつspanで包括します。1文字ずつspanで囲ったテキストをさらに.equalityで包括します。

<table>
  <tr>
    <th>
      <div class="equality">
        <span>均</span><span>等</span><span>割</span><span>付</span>
      </div>
    </th>
    <td>CSSで均等割付</td>
  </tr>
  <tr>
    <th>
      <div class="equality">
        <span>均</span><span>等</span>
      </div>
    </th>
    <td>CSSで均等割付</td>
  </tr>
  <tr>
    <th>
      <div class="equality">
        <span>割</span><span>付</span>
      </div>
    </th>
    <td>CSSで均等割付</td>
  </tr>
</table>

CSSでは、以下のように指定します。

table {
  width: 40%;
  border-collapse: collapse;
}

th,
td {
  padding: 10px 20px;
  color: #333;
  border: solid 1px #aaa;
}

th {
  background: #eaf6ff;
  font-weight: bold;
  font-size: 16px;
  width: 120px;
}

td {
  font-size: 14px;
}

.equality {
  display: flex;
  justify-content: space-between;
}

.equalityに指定した「display: flex;」「justify-content: space-between;」によって、テキストの横並び&両端揃えを実現しています。

ちょっと無理やり感はありますが、この方法だとSafariにも対応しているため、主要ブラウザすべてに対応したい場合はこちらをお試しください。

あとがき

IE・Edge・Safariがtext-align-lastに対応してくれれば簡単なんですけどね(^^; 主要ブラウザをカバーしようと思うと少々面倒です。

1行のテキストを均等割付・両端揃えしたい時は、ぜひ参考にしていただけると幸いです。

この記事が気に入ったら
いいね!してね♪

Twitter で
スポンサードリンク

関連記事

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です