Display: contents 交換兩個元素位置

用了 display: contents 會發生什麼事?

The easiest way to understand what happens when display: contents is used is to imagine the element’s opening and closing tags being omitted from the markup.

使用情境

例如當 h2 title 在不同裝置,顯示位置不一樣的情況。

<div class="hero">
    <div class="hero__content">
        <h2><!-- Title --></h2>
        <p><!-- Desc --></p>
        <a href="#">Order now</a>
    </div>
    <img src="recipe.jpg" alt="">
</div>

使用 CSS display: contents

.hero__content {
    display: contents;
}

By adding that, the .hero__content element is a hidden ghost now. The browser will parse the markup like the following. (但我們的 markup 架構並沒有改變,改變的只有畫面視覺上而已)

視覺上,容器 hero__content 整個 div tag 被移除了,只留下裡面的小孩。

<div class="hero">
    <h2><!-- Title --></h2>
    <p><!-- Desc --></p>
    <a href="#">Order now</a>
    <img src="recipe.jpg" alt="">
</div>

再加上底下的 css 就好 (手機版)

.hero {
    display: flex;
    flex-direction: column;
}

.hero__content {
    display: contents;
}

.hero h2,
.hero img {
    order: -1;
}

桌面版就回復成原本的樣子

@media (min-width: 750px) {
    .hero {
        flex-direction: row;
    }
    
    .hero__content {
        display: initial;
    }
    
    .hero h2,
    .hero img {
        order: initial;
    }
}

Reference

  1. Less Absolute Positioning With Modern CSS - Ahmad Shadeed
    上面的範例出自於這篇,文章裡搜尋 CSS display: contents

  2. How display: contents; Works

1個讚