📝
【CSS】任意の子要素幅に基づいて親要素のwidthを制御するTips
TL;DR
👇のように指定する
.parent {
width: fit-content;
}
.targetChild {
width: 0;
min-width: 100%;
}
before
after
使えるケース
かなり限定的で👇のようなタイトルの下にサブタイトルがあり、タイトルの幅に合わせてサブタイトルの幅を決めたい時などに使えると思います。
<body>
<div class="parent">
<div class="title">優先する要素</div>
<div class="description">優先しない要素優先しない要素優先しない要素優先しない要素</div>
</div>
</body>
親要素でwidth
プロパティを指定してあげる方法がパッと思いつきますが幅の長い方に揃えられてしまったり、幅が動的に変化したりする場合はその方法だと上手くいきません。
解説
index.html
<body>
<div class="parent">
<div class="title">優先する要素</div>
<div class="description">優先しない要素優先しない要素優先しない要素優先しない要素</div>
</div>
</body>
style.css
.parent {
/*flex*/
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
/*border*/
border: 2px solid red;
/*spacing*/
padding: 8px;
+ width: fit-content;
}
.title {
/*typography*/
font-size: 2rem;
font-weight: bold;
}
.description {
/*typography*/
font-style: italic;
+ width: 0;
+ min-width: 100%;
}
-
.description
のwidth: 0
が適用される -
.description
のmin-width: 100%
が適用され、親要素である.parent
の幅まで広がろうとする -
.parent
のwidth: fit-content
が適用され、.title
の幅に合わせて.parent
の幅が決まる
(この時.description
のwidth
は0なので子要素の中で最も幅が広い.title
に合わせて.parent
の幅が決まる) - この時点で
.title
のwidth
と.description
のwidth
が同じになり、.description
も.title
に合わせた幅になる
あとがき
CSSは嫌い奥が深いですね
Discussion