2022 IT 鐵人賽 - [ Day 3 ] [ CSS ] — Flexbox 與 absolute positioning

Daisy
5 min readSep 17, 2022

--

今天是第三天,想跟大家分享的是,在之前的某次練習中,有發現到在 display: flex 的狀態下,如果把某個 flex item 設定 position: absolute ,竟然也會套用到 flex 的對齊。可是不是說 position: absolute 會跳出 normal flow 嗎?怎麼跟我想的不太一樣?

先看 W3C 所說的
As it is out-of-flow, an absolutely-positioned child of a flex container does not participate in flex layout.

The static position of an absolutely-positioned child of a flex container is determined such that the child is positioned as if it were the sole flex item in the flex container, assuming both the child and the flex container were fixed-size boxes of their used size.

…for example, align-self: center; on an absolutely-positioned child of a flex container, auto offsets on the child will center it in the flex container’s cross axis.

第一段是說如果你把 flex item 做絕對定位,那麼它就不會再參與 flex layout。

第二、三段解釋了對 flex item 做絕對定位的話,就如同它是 flex container 中唯一的 flex item,而且仍然適用於 flex 的對齊屬性,例如使用 align-self: center 會產生效果。

先說結論

把 flex item 設定 position: absolute 時,該 flex item 與其他的 flex item 即為不同 layer 層,不參與其他 flex item 的佈局了。

如果沒有使用 top/right/left/bottom 等偏移值,flex container 的對齊屬性一樣對該 flex item 有作用。
反之,使用了偏移值,便以偏移值為主。

範例

假設有個 container,裡面有 5 個 box

<div class=”container”>
<div class=”box-1">box-1</div>
<div class=”box-2">box-2</div>
<div class=”box-3">box-3</div>
<div class=”box-4">box-4</div>
<div class=”box-5">box-5</div>
</div>
  • example 1

一開始先將 container 設定 display: flex、justify-content: flex-start

  • example 2

再把 box-3 設定 position: absolute,先不用偏移值

可以看到 box-3 脫離 normal flow,而且也套用到 justify-content: flex-start

  • example 3

如果又把 container 改成 justify-content: center

可以看到 box 都在中間位置

  • example 4

再把 box-3 設定 align-self: center

可以看得更清楚,box-3 有套用到 flex 的對齊屬性

  • example 5

最後,我使用了偏移值,top: 25%、right: 25%

box-3 便以偏移值為主

下次如果要把 flex item 做絕對定位,就需要注意可能會套用到 flex 的對齊屬性喔!

DEMO

> 參考資料:
W3C — 4.1. Absolutely-Positioned Flex Children
Flexbox and absolute positioning]
CSS-TRICKS — Flexbox and absolute positioning
> 文章同步更新於 2022 IT鐵人賽

--

--