HTML5 Canvas的学习暂时告一段落。新年到来前的这一个多星期时间,我计划献给CSS。
CSS操纵HTML元素布局,简单地说就是用margin或者position来设置元素与元素之间、元素与页面之间的距离,以达到预期的排列效果。下面的示例搭建了一个简单的页面框架:
HTML代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>块级元素布局</title> <link type="text/css" rel="stylesheet" href="layout.css" /> </head> <body> <div id="frame"> <div class="title">title</div> <div class="menu">menu</div> <div class="content">content</div> <div class="nav">navigation</div> <div class="foot">foot</div> </div> </body> </html>CSS代码:
layout.css
body { background: url(bg.jpg) center fixed no-repeat; } #frame { margin: 0 auto; width: 800px; position: relative; } #frame div { border: dotted 1px; margin-bottom: 10px; } .title { width: 800px; height: 100px; } .menu { width: 800px; height: 50px; } .content { width: 595px; height: 800px; } .nav { width: 190px; height: 800px; position: absolute; top: 175px; right: -2px; } .foot { width: 800px; height: 100px; }在本次实践中发现了几个值得注意的问题:- 常用的水平居中操作 ”margin: 0 auto;” 对于body和未设定宽度的块级元素(如div)无效,原因显而易见:水平方向上外边距无法作用于填充满整行的元素。
- 虽然absolute意味绝对,但是position为absolute的元素仍然有参照物,即首个position不为static的父级元素;如果没有,那么它会和fixed一样相对于浏览器窗口进行定位。因此,如果要让某个position需要设置absolute的元素跟随其父级元素移动,就需要先将对父级元素的position进行设置,因为static是默认值。
- position定位与margin布局某种程度上是可以互换的。如上例中的nav可以改写为: