还是讨论mobile web design的话题,对之前的Going Mobile做些补充和修正。因为我的blog模板是完全用HTML5重写的,所有不支持HTML5以及CSS的移动设备浏览器全部忽略,我指的是此文只针对iPhone Safari,Google Android Chrome Lite以及Opera Mini/Mobile这些Modern Browsers。
善用@Media规则
Opera Mini/Mobile, Chrome Lite, iPhone Safari都支持@media
规则,所以下面这行代码基本上就能搞定这些主流的移动设备浏览器了。
@import url(css/handheld.css) only screen and (max-device-width:480px)
如果你希望为iPhone Safari/Chrome Lite添加独立的样式表的话,加上-webkit
prefix就可以了。
@import url(css/handheld_iphone.css) only screen and (-webkit-max-device-width:480px)
Viewport的重要性
由于Opera Mobile的默认screen width是850px,而iPhone Safari则是980px。如果你跟我一样,不设定body
的宽度,而是让它自适应屏幕宽度的话,你会发现在移动浏览器上你的网页宽度可能远远超过了480px。添加viewport
的META到HTML head里能有效避免这个问题。
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, user-scalable=yes" />
通过width=device-width
将网页默认宽度设置为设备屏幕尺寸。
Float and Fixed Positioning
float
能不用尽量不用,但不等于说float
就不能用,至少iPhone Safari,Chrome Lite以及Opera Mini/Mobile对浮动的处理都是很准确的。
真正需要避免的是fixed
定位,一是浪费了原本就不大的屏幕空间,二是滚动页面时容易导致花屏。
使用Max-Width
如果你的图片动辄500px的宽度,在移动设备的浏览器上显示肯定会溢出屏幕,最好的办法是给img
加上max-width
属性:
img {max-width:100%; height:auto;}
充分利用好HTML5 input
HTML5为input加入了很多激动人心的新属性,包括新的type
,placeholder
以及autofocus
。
新的Input类别
新加入的input type包括email
, url
, search
…使用这些type
准确定义你的输入框,不仅让代码更语义化,而且在iPhone Safari上也能获得更大的输入便捷。
例如,如果你的input
定义为email
type:
<input type="email">
在iPhone Safari上点击输入框,弹出的虚拟键盘是这样的:
图片来自Dive into HTML5: A Form of Madness
最下面的一排按钮包括了email地址常用的@
, .
符号。
而如果你的input
定义为url
type的话:
<input type="url">
在iPhone Safari上弹出的虚拟键盘则自动包括了常用的.
,/
,.com
符号。
图片来自Dive into HTML5: A Form of Madness
长摁.com
的话还能在com, org, net中切换,不得不赞叹Apple的工程师对iPhone的细节把握,可惜的是Google Android就没这么聪明了。
Placeholder属性
placeholder
这个新加入的属性可以在input
中加入提示性文字,当点击input
时该提示性文字则自动隐藏。以往这样的功能是需要依赖于javascript才能实现的。
如上图,加入以下代码,在输入框内会出现(Required, will not be published)的提示性文字。
<input type="email" id="email" value="" placeholder="(Required, will not be published)" required />
经测试,iPhone Safari和Chrome Lite都支持该属性。
Autofocus
另一个新增加的input
是autofocus
,目的是在页面加载完后自动聚焦到指定输入框内,这个效果经常在网页账号登陆页面上使用,例如Gmail, WordPress的登陆页面等等。同样,iPhone Safari,Chrome Lite以及Opera Mobile都支持它。
<input id="login" autofocus>
No Font-Face
font-face虽然在iPhone Safari,Chrome Lite以及Opera Mobile下都支持,但是以我的blog为例,即使开启了gzip压缩,一个Graublau Web字体还是有38kb。最好还是为移动样式表重新定义下font-family
,去掉自定义字体。
亲测Safari Mobile不支持属性,怎么破?
具体哪个属性不支持?
这么设置是合法的么,因为使用默认的1.0会使网页像素x2
@iPUNKID autofocus在mobile safari上不支持http://www.wufoo.com/html5/attributes/02-autofocus.html
@ Dolly 这篇日志是好早之前的,我现在都直接锁定scale比例为1.0了。我没有iOS设备,所以未能实测有失准确,Chrome for Android倒是支持autofocus。