两边宽度固定,中间宽度自适应的几种布局方法

我们在用css设置页面布局的时,归根结底是要让页面中的块按照我们的需求进行排列组合。以下是几种常用的中间自适应,两边固定的布局方法。
一、flex弹性盒布局: 核心:将父元素设置为弹性盒布局:display:flex;
html代码:

宽度固定
宽度自适应(用flex弹性盒布局)
宽度固定

css代码:
#father{ display: flex; /*父元素设置为弹性盒*/ flex-wrap: nowrap; /*不换行*/ width: 100vw; height: 30vh; background-color: orange; text-align: center; } #son1{ width: 200px; /*宽度固定*/ height: 30vh; background-color: yellow; } #son2{ height:30vh; width: calc(100vw - 400px); background-color: pink; } #son3{ width: 200px; /*宽度固定*/ height: 30vh; background-color: lightblue; }

二、浮动float 父元素不设置定位,三列子元素都设置为左浮动。
自适应的那一列宽度用计算得出:calc(100vw(100%视窗宽度) - 左边宽度 - 右边宽度)。

html代码:
宽固定(float:left)
自适应(float:left)
宽固定(float:left)

css代码:
#dad{/*父元素不设置定位,子元素浮动*/ width: 100vw; height: 30vh; background-color: orange; text-align: center; } #Left{ float: left; width: 200px; height: 30vh; background-color: lightgreen; } #Center{ float: left; width: calc(100vw - 400px); height: 30vh; background-color: grey; } #Right{ float: left; height: 30vh; width: 200px; background-color: red; }

三、position定位 核心:将父元素设置为position:relative;(相对定位)
子元素设置为绝对定位position:absolute;
左边列(固定宽度):position:absolute; left:0;
中间列(自适应列):position:absolute; left:(左边列的宽度); right:(右边列的宽度)
右边列(固定宽度):position:absolute; right:0;

html代码:
左absolute宽固定
自适应(父元素relative,子元素absolute定位)
右absolute宽固定

【两边宽度固定,中间宽度自适应的几种布局方法】css代码:
#third{ position: relative; /*父元素设置相对定位*/ width: 100vw; height: 40vh; background-color: orange; text-align: center; } #thirdone{ position: absolute; /*子元素绝对定位*/ left: 0; /*与左边距离为0*/ width: 200px; height: 40vh; background-color: blue; } #thirdtwo{ position: absolute; /*子元素绝对定位*/ left: 200px; /*中间的子元素与左右的距离=左右列各自的宽度*/ right: 200px; height: 40vh; background-color: yellow; } #thirdthree{ position: absolute; /*子元素绝对定位*/ right: 0; /*与右边距离为0*/ width: 200px; height: 40vh; background-color: purple; }

    推荐阅读