📝
【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