CSS 響應式設計媒體查詢



在響應式網頁設計中,媒體查詢規則用於根據特定的螢幕寬度、縱橫比和解析度有條件地應用樣式。在本節中,我們將學習如何使用媒體查詢規則設計響應式網頁。

什麼是媒體查詢?

CSS 中的媒體查詢用於根據螢幕大小、解析度以及使用者裝置的其他特性應用不同的 CSS 樣式。媒體查詢使用@media 規則,在滿足特定條件時包含額外的 CSS 屬性塊。

新增斷點

在響應式設計中,**斷點**是佈局發生變化以更好地適應螢幕大小的特定螢幕寬度。我們可以透過定義具有最大或最小寬度的媒體查詢來新增斷點。以下程式碼顯示了確切的語法。

/* Example of a breakpoint for screens smaller than 768px */
@media (max-width: 768px) {
    .container {
        flex-direction: column;
    }
}

在此示例中,當螢幕寬度為 768px 或更小時,`.container` 佈局會更改為列方向。

媒體查詢設定寬度限制

我們可以在媒體查詢中設定寬度限制,以僅在特定的螢幕寬度範圍內應用樣式。透過定義最小和最大寬度,我們可以在所需的螢幕尺寸範圍內控制元素的佈局和外觀。

示例

在以下示例中,當視口寬度大於 35em 且小於 85em 時,body 的背景顏色會更改為李子色。

<!DOCTYPE html>
<html>

<head>
<style>
    body {
        background-color: white; /* Default background */
    }

    @media (min-width: 35em) and (max-width: 85em) {
        body {
            background-color: plum; 
        }
    }
</style>
</head>
<body>
    <h1>Media Query Width Limit Example</h1>
    <p>
        Resize the browser window to see the background 
        color change.
    </p>
    <p> 
        <b> Note: </b>
        If you can't resize here, Run in Tutorialspoint HTML compiler
    </p>
</body>

</html>

媒體查詢多個斷點

透過在媒體查詢中使用多個斷點,我們可以為不同的螢幕尺寸和使用者裝置條件設計佈局樣式。讓我們看一個例子。

示例

在此示例中,我們定義了三個斷點,以調整小型、中型和大型螢幕的字型大小和佈局。

<!DOCTYPE html>
<html>

<head>
<style>
    body {
        font-size: 16px; /* Default font size */
    }

    /* Small screens (up to 600px wide) */
    @media (max-width: 600px) {
        body {
            font-size: 14px;
        }
    }

    /* Medium screens (601px to 900px wide) */
    @media (min-width: 601px) and (max-width: 900px) {
        body {
            font-size: 16px;
        }
    }

    /* Large screens (901px and up) */
    @media (min-width: 901px) {
        body {
            font-size: 18px;
        }
    }
</style>
</head>
<body>
    <h1>Multiple Breakpoints Example</h1>
    <p>
        Resize the browser window to see the background 
        color change.
    </p>
    <p> 
        <b> Note: </b>
        If you can't resize here, Run in Tutorialspoint HTML compiler
    </p>
</body>

</html>

CSS 媒體查詢用於螢幕方向

我們可以為使用者裝置的特定方向(橫向或縱向)定義樣式。此選項的預設值為縱向。

@media (orientation: portrait) {
    /* Styles */
}

示例

以下示例演示了當螢幕寬度大於 500px 且裝置處於橫向方向時,文字顏色會更改為藍色。

<!DOCTYPE html>
<html>

<head>
    <style>
        body {
            color: red;
        }
        @media (min-width: 500px) and (orientation: landscape) {
            body {
                color: blue;
            }
        }
    </style>
</head>

<body>
    <h3>Resize the browser window to see the effect.</h3>
    <p>
        The text color changed to blue when the viewport width is 
        at least 500px and the device is in landscape orientation.
    </p>
    <p> 
    <b> Note: </b>
        If you can't resize here, Run in Tutorialspoint HTML compiler
</p>
</body>

</html>
廣告