作为前端开发人员,如何在各种大小的屏幕上提供一流的用户体验,答案是:采用响应式设计。响应式设计可以随所显示的屏幕大小而改变。实现响应式设计的主要方法是使用 CSS 媒体查询。ie6-8不支持媒体查询。
1,媒体查询的规则:
@media all and (min-width: 800px) { div.example{background-color:red;} }
所有水平屏幕宽度大于800像素的屏幕和打印等都应使用大括号内定义的css规则。all和and可省略不写:@media (min-width:800){...}。
@media only screen and(min-width:800){...}则只针对彩色屏幕设备。
2,可根据需要添加多个条件,如下:
@media (min-width:800px) and (max-width:1200px) and (orientation:portrait) { div.example{background-color:red;} }
所有水平屏幕宽度 大于800像素 并且小于1200像素 并且媒体高度大于宽度时 ,应使用大括号内定义的css规则。此处orientation还可取值landscape,即媒体高度小于宽度。但是iPhone不支持orientation媒体特性。
3,通过媒体查询可以为不同大小和尺寸的媒体定义不同的css,适合相应的设备显示。设置条件的基本语法是制定media类型并在圆括号中设置相对于的条件。
<link rel="stylesheet" href="ipad-portrait.css" media="only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait)">
<link rel="stylesheet" href="iphone4.css" media="only screen and (-webkit-min-device-pixel-ratio : 1.5), only screen and (min-device-pixel-ratio : 1.5)">
附:媒体查询文档
media_query: [only | not]? <media_type> [ and <expression> ]* expression: ( <media_feature> [: <value>]? ) media_type: all | aural | braille | handheld | print | projection | screen | tty | tv | embossed media_feature: width | min-width | max-width | height | min-height | max-height | device-width | min-device-width | max-device-width | device-height | min-device-height | max-device-height | device-aspect-ratio | min-device-aspect-ratio | max-device-aspect-ratio | color | min-color | max-color | color-index | min-color-index | max-color-index | monochrome | min-monochrome | max-monochrome | resolution | min-resolution | max-resolution | scan | grid
设置条件的基本语法是用来指定media类型并在圆括号中设置相应的条件