14. css3 media响应式样式示例

    技术2022-07-10  148

    需求

    在日常的样式编写中,对于浏览器宽度变化的时候,我们为了增加体验,总是需要根据变化进行响应式的样式设置。

    本篇章编写一个 media 的浏览器宽度响应示例。

    media 使用说明

    @media 类型 and (条件1) and (条件二){*/ css样式*/ }

    上面写的类型有很多种,不过我们一般只需要认识一下屏幕的变化即可,示例如下:

    /* 如果文档宽度小于 300 像素则修改背景颜色(background-color): */ @media screen and (max-width: 300px) { body { background-color:lightblue; } }

    这是一个最典型根据屏幕的宽度变化,来设置样式的示例。 下面我们来继续丰富这个示例,根据不同的浏览器宽度,变化 body 的背景色。

    示例代码

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> /*@media 类型 and (条件1) and (条件二){*/ /* css样式*/ /*}*/ /*Extra small 当浏览器的最大宽度为 <576px, 则设置 body 背景色为 red*/ @media only screen and (max-width:576px) { body{ background-color: red; } } /*Small 当浏览器的最大宽度为 ≥576px, 则设置 body 背景色为 blue*/ @media only screen and (min-width:576px) { body{ background-color: blue; } } /*Medium 当浏览器的最大宽度为 ≥768px, 则设置 body 背景色为 cyan*/ @media only screen and (min-width:768px) { body{ background-color: cyan; } } /*Large 当浏览器的最大宽度为 ≥992px, 则设置 body 背景色为 greenyellow*/ @media only screen and (min-width:992px) { body{ background-color: greenyellow; } } /*Extra large 当浏览器的最大宽度为 ≥1200px, 则设置 body 背景色为 sandybrown*/ @media only screen and (min-width:1200px) { body{ background-color: sandybrown; } } </style> </head> <body> <div style="margin-top: 10px"> <span>响应式样式:Extra small,当浏览器的最大宽度为 <576px, 则设置 body 背景色为 red</span> <div style="display: inline-block;width: 15px; height: 15px; border-radius: 50%; border: 1px solid #ccc; background: red;"></div> </div> <div style="margin-top: 10px"> <span>响应式样式:Small,当浏览器的最大宽度为 ≥576px, 则设置 body 背景色为 blue</span> <div style="display: inline-block;width: 15px; height: 15px; border-radius: 50%; border: 1px solid #ccc; background: blue;"></div> </div> <div style="margin-top: 10px"> <span>响应式样式:Medium,当浏览器的最大宽度为 ≥768px, 则设置 body 背景色为 cyan</span> <div style="display: inline-block;width: 15px; height: 15px; border-radius: 50%; border: 1px solid #ccc; background: cyan;"></div> </div> <div style="margin-top: 10px"> <span>响应式样式:Large,当浏览器的最大宽度为 ≥992px, 则设置 body 背景色为 greenyellow</span> <div style="display: inline-block;width: 15px; height: 15px; border-radius: 50%; border: 1px solid #ccc; background: greenyellow;"></div> </div> <div style="margin-top: 10px"> <span>响应式样式:Extra large,当浏览器的最大宽度为 ≥1200px, 则设置 body 背景色为 sandybrown</span> <div style="display: inline-block;width: 15px; height: 15px; border-radius: 50%; border: 1px solid #ccc; background: sandybrown;"></div> </div> </body> </html>

    效果如下:

    GIF 2020-6-30 15-11-26.gif
    Processed: 0.011, SQL: 9