双飞翼布局和神圣罗马布局都是适用负外边距来实现的,都有一个共同的基础。
下面是其相同的代码:
<!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> </head> <style type="text/css"> .main{width:100%;height:80px;background-color:#00f; float:left; } .side{width:190px;height:80px;background-color:#F00;; float:left; margin-left:-100%; } .exta{width:320px;height:80px;background-color:#0f0; float:left; margin-left:-320px;//这是margin-left而不是margin-right } </style> <body> <div class="main">main</div> <div class="side">side</div> <div class="exta">exta</div> </body> </html>
效果如下图,这是一个三列布局,main先显示,并把它放在中间位置,这是这个三列布局的最终目的,主要是“重要内容先加载”。
而上图效果显然没有达到,main中的内容显然没有显示,因为其被遮住了,要解决这个问题有两种方式,第一种是采用神圣罗马布局的方式:如下
<!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> </head> <style type="text/css"> .main{width:100%;height:80px;background-color:#00f; float:left; } .side{width:190px;height:80px;background-color:#F00;; float:left; margin-left:-100%; } .exta{width:320px;height:80px;background-color:#0f0; float:left; margin-left:-320px; } .pd{padding:0 320px 0 190px;} </style> <body> <div class="pd"> <div class="main">main</div> <div class="side">side</div> <div class="exta">exta</div> </div> </body> </html>
给容器添加padding使得左右两边留够side exta的宽度。然后下一步采用相对位置的方式把side exta 向两边留有的余量移动。
<style type="text/css"> .main{width:100%;height:80px;background-color:#00f; float:left; } .side{width:190px;height:80px;background-color:#F00;; float:left; margin-left:-100%; position:relative; right:190px; } .exta{width:320px;height:80px;background-color:#0f0; float:left; margin-left:-320px; position:relative;left:320px; } .pd{padding:0 320px 0 190px;} </style>
达成效果。
第二种方式是淘宝使用的双飞翼模式:
<!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> </head> <style type="text/css"> .main{width:100%;height:80px;background-color:#00f; float:left; } .side{width:190px;height:80px;background-color:#F00;; float:left; margin-left:-100%; } .exta{width:320px;height:80px;background-color:#0f0; float:left; margin-left:-320px; } .main_content{padding:0 320px 0 190px;} </style> <body> <div class="pd"> <div class="main"> <div class="main_content"> main</div> </div> <div class="side">side</div> <div class="exta">exta</div> </div> </body> </html>
这种方式只是在main里面内嵌了一个div标签,然后通过padding属性定位main 的位置,达到要求。