📝

【CSS】任意の子要素幅に基づいて親要素のwidthを制御するTips

2025/01/16に公開

TL;DR

👇のように指定する

.parent {
  width: fit-content;
}

.targetChild {
  width: 0;
  min-width: 100%;
}

before

before

after

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%;
}
  1. .descriptionwidth: 0が適用される
  2. .descriptionmin-width: 100%が適用され、親要素である.parentの幅まで広がろうとする
  3. .parentwidth: fit-contentが適用され、.titleの幅に合わせて.parentの幅が決まる
    (この時.descriptionwidthは0なので子要素の中で最も幅が広い.titleに合わせて.parentの幅が決まる)
  4. この時点で.titlewidth.descriptionwidthが同じになり、.description.titleに合わせた幅になる

あとがき

CSSは嫌い奥が深いですね

GitHubで編集を提案
SMARTCAMP Engineer Blog

Discussion