Catalog
  1. 1. 自适应布局的解决方案
    1. 1.1. 一列定宽 一列自适应
      1. 1.1.1. float + margin
      2. 1.1.2. float + overflow
      3. 1.1.3. table
      4. 1.1.4. flex
    2. 1.2. 一列不定宽 一列自适应
      1. 1.2.1. float + overflow
      2. 1.2.2. table
      3. 1.2.3. flex
  2. 2. 等宽布局的解决方案
    1. 2.1. float
    2. 2.2. table
    3. 2.3. flex
  3. 3. 等高布局的解决方案
    1. 3.1. table
    2. 3.2. flex
    3. 3.3. float
css布局解决方案

自适应布局的解决方案

页面结构如下:

<div class="parent">
<div class="left">
<p>left</p>
</div>
<div class="right">
<p>right</p>
<p>right</p>
</div>
</div>

一列定宽 一列自适应

float + margin

.left{
float: left;
width: 100px;
}
.right{
margin-left: 120px;
}

float + overflow

.left{
float: left;
width: 100px;
margin-right: 20px;
}
.right{
overflow: hidden; // 触发BFC
}

table

.parent{
display: table;
width: 100%;
table-layout: fixed; // 让内容优先,不设置默认由内容决定宽度
}
.left,
.right{
display: table-cell;
}
.left{
width: 100px;
padding-right: 20px;
}

flex

.parent{
display: flex;
}
.left{
width: 100px;
margin-right: 20px;
}
.right{
flex: 1;
}

一列不定宽 一列自适应

float + overflow

.left{
float: left;
margin-right: 20px;
}
.right{
overflow: hidden; // 触发BFC
}

table

.parent{
display: table;
width: 100%;
}
.left,
.right{
display: table-cell;
}
.left{
width: 0.1%; // 没有设置table-layout: fixed;内容优先由内容决定宽度
padding-right: 20px;
}
.left p{
width: 100px; // 父元素table特性会跟着内容变化
}

flex

.parent{
display: flex;
}
.left{
margin-right: 20px;
}
.right{
flex: 1;
}

等宽布局的解决方案

页面结构如下:

<div class="parent-fix">
<div class="parent">
<div class="column"><p>1</p></div>
<div class="column"><p>2</p></div>
<div class="column"><p>3</p></div>
<div class="column"><p>4</p></div>
</div>
</div>

float

.parent{
margin-left: -20px;
}
.column{
float: left;
width: 25%;
padding-left: 20px;
box-sizing: border-box;
}

table

.parent-fix{
margin-left: -20px;
}
.parent{
display: table;
width: 100%;
table-layout: fixed; // 布局优先单元格会等宽
}
.column{
display: table-cell;
padding-left: 20px;
}

flex

.parent{
display: flex;
}
.column{
flex: 1;
}
.column + .column{
margin-left: 20px;
}

等高布局的解决方案

页面结构如下:

<div class="parent">
<div class="left">
<p>left</p>
</div>
<div class="right">
<p>right</p>
<p>right</p>
</div>
</div>

table

.parent{
display: table;
width: 100%;
table-layout: fixed;
}
.left,
.right{
display: table-cell;
}
.left{
width: 100px;
border-right: 20px solid transparent;
background-clip: padding-box;
}

flex

.parent{
display: flex; // 利用align-items默认属性stretch元素被拉伸以适应容器的特性
}
.left{
width: 100px;
margin-right: 20px;
}
.right{
flex: 1;
}

float

.left{
float: left;
width: 100px;
margin-right: 20px;
}
.right{
overflow: hidden;
}
.left,
.right{
// 无限大伪等高
padding-bottom: 9999px;
margin-bottom: -9999px;
}
.parent{
overflow: hidden;
}
Author: 匡凡
Link: https://kuangfan.github.io/2019/12/18/css/css%E5%B8%83%E5%B1%80%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
  • 支付宝