CSS 寬度自適應: max-width、min-width、fit-content 介紹

前言

在 CSS3 中新增了幾個設置寬度屬性的關鍵字:max-widthmin-widthfit-content 就讓我們來一一了解這些觀念吧!

注意:這裡的「寬度」指的是語意上的寬度,而不是 CSS 的 width,也就是說,如果文字方向是垂直的或在 flexbox 或 Grid 中,這些值也對 CSS 的 height 有效。另外,它們在 min-width、min-height、max-width、max-height 中也都是有效的。

max-content:寬度等於內容最大寬度

The max-content sizing keyword represents the intrinsic maximum width or height of the content. For text content this means that the content will not wrap at all even if it causes overflows. –MDN Web Docs

max-content 表示內容固有的最大的寬度或高度,以 text 內容來說,就算會溢出(overflow)也不會換行。

我們可以從下面的範例中看到,當我們在 item 加上 max-content 後,文字便不會換行,做用和 white-space:nowrap 很相似。

See the Pen by 蔡蔡 Mavis (@0430shinyu) on CodePen.

min-content:寬度等於內容最小寬度

The smallest size a box could take that doesn’t lead to overflow that could be avoided by choosing a larger size. — W3C

min-content 表示最小不會造成溢出(overflow)的寬度。對於文字(text)內容來說,會變得與最長的單詞一樣的寬度。

以下面這個範例來看,我們可以看到加上了 min-contentitem ,會以最長單字(consecteturctetur)的寬度作為 item 的寬度。

See the Pen css-max-content-demo by 蔡蔡 Mavis (@0430shinyu) on CodePen.

再來我們可以查看下方這個範例,會發現未加上 min-content 的區塊元素 item 會繼承父成的寬度 ,而加上了 min-content 的 item 則以圖片的寬度做為 item 的寬度,這是因為 width:100px 的圖片是最小不會造成溢出(overflow)的寬度。

See the Pen css-min-content-demo by 蔡蔡 Mavis (@0430shinyu) on CodePen.

fit-content:依照內容寬度伸縮

The fit-content behaves as fit-content(stretch). In practice this means that the box will use the available space, but never more than max-content. –MDN Web Docs

fit-content 會讓元素使用可用空間,但不會大於 max-content。

在下面這個範例中可以看到,區塊元素 item 加上 fit-content 後,寬度會與內容寬度相同。

See the Pen css-fill-available by 蔡蔡 Mavis (@0430shinyu) on CodePen.

這個特性在處理區塊水平置中上非常方便

See the Pen css-fit-content-demo by 蔡蔡 Mavis (@0430shinyu) on CodePen.

結語

最後,在針對三個做個總結:

  1. max-content:寬度等於子元素最小寬度
  2. min-content:寬度等於子元素最大寬度
  3. fit-content:
    如果可用空間比max-content大,寬度就等於 max-content
    如果可用空間比max-content小,寬度就等於可用空間的寬,
    如果可用空間比min-content小,那麼寬度就等於 min-content

參考資料

How do min-content and max-content work?


CSS 寬度自適應: max-width、min-width、fit-content 介紹
https://shinyu0430.github.io/2021/09/21/maxwidthminwidthfitcontent/
作者
Mavis Tsai
發布於
2021年9月21日
許可協議