面试:如何实现两栏布局

1,058 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

面试中常见的一道 css 布局的问题-如何实现两栏布局?

当你遇到这个问题,会不会突然的卡壳呢😅😅 今天就来聊一聊几种常见的实现方式。

话不多多说,先看完整效果图:

image.png

左浮动(float: left)+ 右侧overflow(overflow: hidden)

// html
<div>
  <div className='left'></div>
  <div className='right'></div>
</div>
// css
.left {
  width: 180px;
  height: 60px;
  background-color: cadetblue;
  float: left;
}
.right {
  height: 60px;
  background-color: chocolate;
  overflow: hidden;
}

左浮动 float + 右 marginLeft

<div>
  <div className='f1'></div>
  <div className='f2'></div>
</div>

.f1 {
  float: left;
  width: 120px;
  height: 50px;
  background-color: darkblue;
}
.f2 {
  margin-left: 120px;
  height: 50px;
  background-color: darkgreen;
}

左浮动float + 右float(width: calc(100% - width))

左侧左浮动;右侧右浮动宽度使用calc()计算

<div style={{overflow: 'hidden'}}>
  <div className='f3'></div>
  <div className='f4'></div>
</div>

.f3 {
  float: left;
  width: 120px;
  height: 40px;
  background-color: darkblue;
}
.f4 {
  float: right;
  width: calc(100% - 120px);
  height: 40px;
  background-color: darkgreen;
}

flex布局

利用flex属性,左侧固定宽度,右侧自适应

<div className='parent'>
  <div className='child1'></div>
  <div className='child2'></div>
</div>

.parent {
  display: flex;
}
.child1 {
  width: 200px;
  height: 50px;
  background-color: cornflowerblue;
}
.child2 {
  flex: 1;
  height: 50px;
  background-color: cyan;
}

绝对定位

左侧固定宽度,右侧使用marginLeft撑起

<div className='container'>
  <div className='positionLeft'></div>
  <div className='positionRight'></div>
</div>
.container {
  position: relative;
  width: 100%;
}
.positionLeft {
  position: absolute;
  top: 0;
  left: 0;
  width: 100px;
  height: 60px;
  background-color: darkslategray;
}
.positionRight {
  margin-left: 100px;
  height: 60px;
  background-color: darkviolet;
}

table布局

利用table属性,父元素设置display: table,子元素设置display: table-cell

<div className='table'>
  <div className='tableLeft'></div>
  <div className='tableRight'></div>
</div>

.table {
  display: table;
  width: 100%;
  height: 60px;
}
.tableLeft {
  display: table-cell;
  width: 100px;
  background-color: burlywood;
}
.tableRight {
  display: table-cell;
  background-color: cornflowerblue;
}

Grid布局

设置父元素display: grid, grid-template-columns指定页面分成两列。

第一列的宽度是minmax(150px, 150px),即最小宽度为150px,最大宽度为总宽度的150px;

第二列为 1fr,即所有剩余宽度

<div className='grid'>
  <div className='gridLeft'>left</div>
  <div className='gridRight'>right</div>
</div>
.grid {
  display: grid;
  grid-template-columns: minmax(150px, 150px) 1fr;
}
.gridLeft {
  background-color: darkgreen;
}
.gridRight {
  background-color: darkolivegreen;
}

结语

如果这篇文章帮到了你,欢迎点赞👍和关注⭐️。

文章如有错误之处,希望在评论区指正🙏🙏。