どうも、くまだです。
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があると | 加算されることがある | 自動で引いてくれる |
ここまで読んでくださりありがとうございました。