media为不同设备指定不同样式
<link rel="stylesheet" href="common.css">
<link rel="stylesheet" href="screen.css" media="screen">
<link rel="stylesheet" href="print.css" media="print">
common.css存放公共样式,screen.css和print.css分别指定屏幕和打印样式。media="screen, print"和media="all"以及不加media效果一样
使用@import简化样式引入
@import 可以引入指定设备的样式规则
style.css
@import url(common.css) all;
@import url(screen.css) screen;
@import url(print.css) print;
index.html
<link rel="stylesheet" href="style.css">
查询条件
<style media="screen and (min-width:768px)"></style>
<style media="screen and (max-width:768px)"></style>
media="screen and (min-width:768px)"指定屏幕尺寸大于768px应用的样式
注意:屏幕尺寸等于768px将应用样式2,因为后面设置覆盖前面设置
- 逻辑与
需要满足多个条件时才使用样式,多个条件使用and连接
@media screen and (orientation: landscape) and (max-width: 600px){}
横屏并且最大宽度小于600px应用的宽度
- 逻辑或
多个或条件查询使用逗号,连接
@media screen and (orientation: landscape),
screen and (max-width: 600px){}
表示屏幕横屏或者小于600px应用的样式
- not关键字
not表示不应用样式,必须将not写在查询的最前面,即所有条件都满足时不应用样式
@media not screen and (orientation: landscape) and (max-width:600px){}
- only
用来排除不支持媒体查询的浏览器,和not一样必须写在最前面
@media only screen and (orientation: landscape) and (max-width: 600px) {}
常用特性
下面列出常用的媒体查询特性
| 特性 | 说明 |
|---|---|
| orientation | landscape横屏,portrait竖屏 |
| width | 设备宽度 |
| height | 设备高度 |
| min-width | 最小宽度 |
| max-width | 最大宽度 |
| min-height | 最小高度 |
| max-height | 最大高度 |
媒体查询出现次序
统一用min-width,屏幕较大的样式写在下方
/* 屏幕小于768px应用样式 */
@import url("small-x.css") only screen and (max-width: 768px);
@import url("small.css") only screen and (min-width: 768px);
@import url("media.css") only screen and (min-width: 960px);
@import url("large.css") only screen and (min-width: 1200px);
使用rem单位
:root相当于html
:root {
font-size: 15px;
}
设置的html的font-size为15px,间接的将1rem设置为15px
css实现导航栏显示隐藏
html
<div class="navbar">
<a href="" class="logo">houdunren</a>
<label for="toggle-nav">
<i class="fa fa-tasks" aria-hidden="true"></i>
</label>
<input type="checkbox" id="toggle-nav" />
<div class="collapse">
<ul class="links">
<li><a href="">在线教程</a></li>
<li><a href="">社区讨论</a></li>
<li><a href="">八点直播</a></li>
<li><a href="">实战课程</a></li>
</ul>
<div class="form">
<a href="">登录</a>
<a href="" class="form-bg">注册</a>
</div>
</div>
</div>
css
header .navbar .logo + label + input:checked + .collapse {
display: block;
}
header .navbar .collapse {
display: none;
flex-flow: column;
width: 100%;
}
input:checked在在元素点击之后触发
合并边框
margin-left:-1px;
设置负边距可以合并边框
使用rem作为单位
rem参照html的font-size,默认1rem=16px,便于修改整体字体大小