2008年7月27日星期日

CSS 浮动清理

在进行浮动布局时,大多数人都深知,在必要的地方进行浮动清理:<div style="clear:both;"></div>。
例如:
<div style="background:#666;"> <!-- float container -->
<div style="float:left; width:30%; height:40px;background:#EEE; ">Some Content</div>
</div>
此时预览此代码,我们会发现最外层的父元素float container,并没有显示。这是因为子元素因进行了浮动,而脱离了文档流,导致父元素的height为零。
若将代码修改为:
<div style="background:#666;"> <!-- float container -->
<div style="float:left; width:30%; height:40px;background:#EEE; ">Some Content</div>
<div style="clear:both"></div>
</div>
注意,多了一段清理浮动的代码。这是一种好的CSS代码习惯,但是这种方法增加了无用的元素。这里有一种更好的方法,将HTML代码修改为:
<div class="clearfix" style="background:#666;"> <!-- float container -->
<div style="float:left; width:30%; height:40px;background:#EEE; ">Some Content</div>
</div>
定义CSS类,进行“浮动清理”的控制:
.clearfix:after {
content: ".";
clear: both;
height: 0;
visibility: hidden;
display: block;
} /* 这是对Firefox进行的处理,因为Firefox支持生成元素,而IE所有版本都不支持生成元素 */
.clearfix {
display: inline-block;
} /* 这是对 Mac 上的IE浏览器进行的处理 */
/* Hides from IE-mac \*/
* html .clearfix {height: 1%;} /* 这是对 win 上的IE浏览器进行的处理 */
.clearfix {display: block;} /* 这是对display: inline-block;进行的修改,重置为区块元素*/
/* End hide from IE-mac */

2008年7月8日星期二

Cache-Control, Expires

FROM: “Cache-control”常见的取值有private、no-cache、max-age、must-revalidate等

Cache-Control


网页的缓存是由 HTTP 消息头中的 Cache-Control 来控制的,常见的取值有 privateno-cachemax-agemust-revalidate等,默认为 private。其作用根据浏览方式不同分为以下几种情况:

打开新窗口

值为 privateno-cachemust-revalidate时,打开新窗口访问时都会重新访问服务器。而如果指定了 max-age 值,那么在此值内的时间里就不会重新访问服务器,例如:Cache-Control: max-age=5 (表示当访问此网页后的 5 秒内再次访问不会去服务器)

在地址栏回车


  • privatemust-revalidate 只有第一次访问时会访问服务器,以后就不再访问。

  • no-cache 每次都会访问。

  • max-age 则在过期之前不会重复访问。



按后退按扭


  • privatemust-revalidatemax-age 不会重访问。

  • no-cache 每次都重复访问。




按刷新按扭

无论为何值,都会重复访问。

Cache-Control 值为 no-cache 时,访问的页面不会在 IE 临时文件夹中留下页面备份 (Firefox、Chrome 会留下)。

另外,通过指定 Expires 值也会影响到缓存。例如,指定 Expires 值为一个过去的时间,那么访问此网时若重复在地址栏按回车,那么每次都会重复访问。

Expires


如果服务器上的网页经常变化,把 Expires 设置为 -1,表示立即过期。如果一个网页每天凌晨 1 点更新,可以把 Expires 设置为第二天的凌晨 1 点。

当 HTTP1.1 服务器指定 CacheControl: no-cache 时,浏览器就不会缓存该网页。HTTP 1.0 服务器不能使用 Cache-Control。所以为了向后兼容 HTTP 1.0 服务器,IE 使用 Pragma: no-cache 以对 HTTP 1.0 提供特殊支持。

如果客户端通过安全连接 (与服务器通讯,且服务器在响应中返回 Pragma:no-cache,则 IE不会缓存此响应。注意: Pragma:no-cache 仅当在安全连接中使用时才防止缓存,如果在非安全页中使用,处理方式与 Expires:-1 相同,该页将被缓存,但被标记为立即过期。

禁止页面在 IE 中缓存,header 响应消息头部设置:
[html]
CacheControl: no-cache
Pragma: no-cache
Expires: -1
[/html]