0%

Media Query

Media query

media query 用來解決不同寬度下的 CSS

html

1
<!DOCTYPE html>
2
<html lang="zh">
3
  <head>
4
    <meta charset="UTF-8" />
5
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
7
    <title>Document</title>
8
    <link rel="stylesheet" href="style.css" />
9
  </head>
10
  <body>
11
    <h1 class="title">Title</h1>
12
    <p class="content">
13
      Lorem, ipsum dolor sit amet consectetur adipisicing elit. Consectetur
14
      voluptatem expedita, earum nihil sunt quaerat debitis deserunt voluptate
15
      itaque aspernatur
16
    </p>
17
  </body>
18
</html>

css

1
.title {
2
  color: red;
3
}
4
5
.content {
6
  color: black;
7
}
8
9
10
@media (max-width: 786px) {
11
  .title {
12
    color: blue;
13
  }
14
  .content {
15
    color: orange;
16
  }
17
}

結果

寬度大於 786px(872px)

title 呈現紅色樣式

web

寬度小於 786px (380px)

title 呈現藍色樣式,且原本的 color:red 也被槓掉,由此得知,media query 會依照設定寬度給予樣式權重

phone