美文网首页
媒体查询

媒体查询

作者: 扶得一人醉如苏沐晨 | 来源:发表于2023-03-30 09:30 被阅读0次

一、媒体类型

image.png
        /* 只有在打印机或打印预览才应用的样式 */
        @media print {
            h1 {
                background: transparent;
            }
        }

        /* 只有在屏幕上才应用的样式 */
        @media screen {
            h1 {
                font-family: "翩翩体-简";
            }
        }

        /* 一直都应用的样式 */
        @media all {
            h1 {
                color: red;
            }
        }

二、媒体特性

image.png
      /* 检测到视口的宽度为800px时,应用如下样式 */
      @media (width: 800px) {
        h1 {
          background-color: green;
        }
      }

      /* 检测到视口的宽度小于等于700px时,应用如下样式 */
      @media (max-width: 700px) {
        h1 {
          background-color: orange;
        }
      }

      /* 检测到视口的宽度大于等于900px时,应用如下样式 */
      @media (min-width: 900px) {
        h1 {
          background-color: deepskyblue;
        }
      }

      /* 检测到视口的高度等于800px时,应用如下样式 */
      @media (height: 800px) {
        h1 {
          background-color: yellow;
        }
      }

      /* 检测到屏幕的宽度等于1536px时,应用如下样式 */
      @media (device-width: 1536px) {
        h1 {
          color: white;
        }
      }

三、运算符

image.png
       /* 且运算符 */
      @media (min-width: 700px) and (max-width: 800px) {
        h1 {
          background-color: orange;
        }
      }
      @media screen and (min-width: 700px) and (max-width: 800px) {
        h1 {
          background-color: orange;
        }
      }

      /* 或运算符 */
      @media screen and (max-width: 700px) or (min-width: 800px) {
        h1 {
          background-color: orange;
        }
      }

      /* 否定运算符 */
      @media not screen {
        h1 {
          background-color: orange;
        }
      }

      /* 肯定运算符 */
      @media only screen and (width: 800px) {
        h1 {
          background-color: orange;
        }
      }

四、常用阈值

在实际开发中,会将屏幕划分成几个区间,例如:


image.png

五、用法

5.1、 结合外部样式的用法

 <link rel="stylesheet" media="screen and (min-width:1200px)" href="./css/huge.css">

huge.css

/* 超大屏幕 */
h1 {
    background-color: purple;
}

5.2、直接通过外部样式引入

注意:媒体查询就是在特定条件下执行的样式,和普通css无差别,具有css的覆盖性,所以写的时候要注意不同条件下的书写顺序,防止被覆盖(css代码越往下条件越苛刻(条件越多))

 <link rel="stylesheet" href="./css/index.css" />

index.css

* {
    margin: 0;
    padding: 0;
}
h1 {
    height: 200px;
    background-color: gray;
    text-align: center;
    line-height: 200px;
    font-size: 100px;
}
/* 超小屏幕 */
@media screen and (max-width:768px) {
    h1 {
        background-color: orange;
    }
}
/* 中等屏幕 */
@media screen and (min-width:768px) and (max-width:992px) {
    h1 {
        background-color: green;
    }
}
/* 大屏幕 */
@media screen and (min-width:992px) and (max-width:1200px) {
    h1 {
        background-color: deepskyblue;
    }
}
/* 超大屏幕 */
h1 {
    background-color: purple;
}

相关文章

网友评论

      本文标题:媒体查询

      本文链接:https://www.haomeiwen.com/subject/ffufddtx.html