# 圣杯布局和双飞翼布局

  • 圣杯:中间padding+左侧margin-left&position+右侧margin-right

  • 双飞翼: 多一个div包裹,中间元素margin+左侧margin-left+右侧margin-left

  • 两侧宽度固定,中间宽度自适应

  • 中间部分在DOM结构上优先,以便先行渲染

  • 允许三列中的任意一列成为最高列

<style>
*{
	margin:0;
	padding:0
}
#container {
  padding-left: 200px; 
  padding-right: 150px;
}
#container .column {
  float: left;
}

#center {
  width: 100%;
  background:greenyellow
}


#left {
  width: 200px; 
  /* 相对于父级的100% */
  /* 本来应该和center同一排,以为center占满了 */
  /* 现在掉下去后又忘往左移,超过宽度就挤上去了 */
  /* 正好和center左侧重合 */
  margin-left: -100%;
  position: relative;
  /* 再往左移动200px */
  right: 200px;
  background: skyblue;
}
#right {
  width: 150px; 
  /* 相当于宽度在后来的div完全遮盖,虽然没有后面div不过可以这么理解 */
  /* 没有了宽度,自然可以和center同一排 */
  margin-right: -150px; 
  background: mediumvioletred;
}

#footer {
  clear: both;
}

</style>
<div id="header">header</div>
<div id="container">
  <div id="center" class="column">1</div>
  <div id="left" class="column">2</div>
  <div id="right" class="column">3</div>
</div>
<div id="footer">footer</div>
<style type="text/css">
	body {
  min-width: 500px;
}

#container {
  width: 100%;
}

.column {
  float: left;
}
        
#center {
  margin-left: 200px;
  margin-right: 150px;
  background:green
}
        
#left {
  width: 200px; 
  margin-left: -100%;
  background: #00D6B2;
}
        
#right {
  width: 150px; 
  margin-left: -150px;
  background: indianred
}
        
#footer {
  clear: both;
}
</style>
<body>
  <div id="header"></div>
  <div id="container" class="column">
    <div id="center">1</div>
  </div>
  <div id="left" class="column">2</div>
  <div id="right" class="column">3</div>
  <div id="footer"></div>
<body>

不考虑兼容性,可直接用flex或者计算属性来代替,也可以左右两部分定位,中间给百分比宽度,padding:0 x px

参考链接 (opens new window)

本地参考

最后更新: 4/18/2024, 9:03:19 AM