CSS布局(圣杯/双飞翼)

1,576 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第19天,点击查看活动详情

布局特点:

内容区分为左中右三部分,其中左右两部分的宽度固定,中间部分的宽度随视口变化

优缺点

  • 圣杯布局用定位+位移,代码较复杂,但是dom结构清晰
  • 双飞翼布局,不使用定位,换来dom结构的不友好

圣杯:

  • 多个div标签
  • 中间宽度center设置为100%,外面的content设置padding,给两端留出位置,留的宽度刚好为左右固定的宽度;
  • center,left,right设置浮动,floor设置clear:both清除浮动;
  • left设置margin-left:-100%,此时left位于center内的左端,;再设置定位position:relative;left:-100px
  • right设置margin-right:-100px
<body>
	<div class="top">top</div>
	<div class="content">
		<div class="center float">center</div>
		<div class="left float">left</div>
		<div class="right float">right</div>
	</div>
	<div class="floor">floor</div>
</body>
.body{margin:0;padding:0}

.float{float:left}

.top{background:#ff2}

.floor{background:#1121d1;clear:both}

.top,.floor{height:50px;width:100%}

.content{padding:0 100px}

.center{width:100%;background:rgb(129,55,55)}

.left{position:relative;background:rgb(1,55,55);width:100px;margin-left:calc(-100%);right:100px}

.right{background:rgb(1,155,155);width:100px;margin-right:-100px}

双飞翼

  • 多个div标签;
  • container设置width:100%,center设置width100%;margin:0 100px;
  • container,left,right设置浮动,footer清除浮动
  • left设置margin-left:100%
  • right设置margin-left:-100px
<body>
	<div class="header">header</div>
	<div class="container float">
		<div class="center">center</div>
	</div>
	<div class="left float">left </div>
	<div class="right float">column</div>
	<div class="footer">footer</div>
</body>
.header{height:50px;background:#ff9;width:100%}

.footer{height:50px;background:rgb(24,24,1);clear:both;width:100%}

.left{width:100px;background:rgb(60,51,189);margin-left:-100%}

.right{width:100px;background:rgb(23,160,160);margin-left:-100px}

.footer{height:50px;background:rgb(24,24,1);clear:both;width:100%}

.float{float:left;height:50px}

.container{width:100%}

.center{height:100%;margin-left:100px;margin-right:100px;background-color:pink}

flex实现

  • flex-grow 用于设置项目的放大系数。
  • flex-shrink 用于设置项目的缩小系数。
  • flex-basis 用于设置项目在主轴上的空间。
  • flex: flex-grow flex-shrink flex-basis | auto | none。 auto 表示:1 1 auto,即等比例扩大或者压缩。 none 表示:0 0 auto,即不扩大,也不压缩。
  • order: 为整数,可以为负数,order 默认值为 0, 用于是设置项目的排序顺序,从小到大排列

  • content设置display:flex
  • center设置flex:1
  • left设置flex: 0 0 100px,order:-1
  • right设置 flex: 0 0 100px
   <div class="content">
		<div class="center">center</div>
		<div class="left column">left100 </div>
		<div class="right column">column150</div>
	</div>
   .content {
		display: flex;
	}

	.center {
		flex: 1;
		background: #ddd;
	}

	.left {
		flex: 0 0 100px;
		order: -1;
		background: #dd0;
	}

	.right {
		flex: 0 0 100px;
		background: #1d0;
	}