【CSS】width: stretchで要素を親いっぱいに広げる

どうも、くまだです。

width: stretch;を使って要素を親要素いっぱいに広げる方法のメモ。

width: 100%だとはみ出る問題

「親いっぱいに広げたい」とき、まず思いつくのがwidth: 100%

でもmarginがあるとこうなる。

    <div class="container">
      <div class="parent">
        <div class="child"></div>
      </div>
    </div>
.container {
    padding: 80px;
}

.parent {
    width: 500px;
    height: 200px;
    background: #eee;
}

.child {
    width: 100%;
    /* 500px + 左右20px = 540px になってはみ出る */
    margin: 0 20px;
    background: orange;
    height: 50px;
}

width: 100%は親の幅をそのままコピーするだけなので、marginが加算されてはみ出てしまう。

width: stretchで解決

width: stretchは「使える空間いっぱいに広がる」イメージ。marginがあれば自動的に引いてくれる。

.child {
    width: stretch;
    /* 500px - 左右20px = 460px にきれいに収まる */
    margin: 0 20px;
    background: orange;
    height: 50px;
}

まだブラウザ対応が不完全なので、ベンダープレフィックスが必要です。

.child {

  /* 古い書き方(フォールバック) */
  width: -webkit-fill-available; /* Chrome・Safari */
  width: -moz-available;         /* Firefox */

  /* 標準の書き方 */
  width: stretch;
}

width: 100%; との比較はこちら。

width: 100%width: stretch
計算の基準親の幅をコピー使える空間に合わせる
marginがあるとはみ出ることがある自動で引いてくれる
paddingがあると加算されることがある自動で引いてくれる

ここまで読んでくださりありがとうございました。

この記事を書いた人