CSS-常见布局

184 阅读2分钟

在前端开发中,实现元素的水平垂直居中、左侧固定宽度右侧自适应、以及三列均分布局是非常常见的需求。以下是这些布局的实现思路和代码示例:


1. 元素水平垂直居中

实现元素的水平垂直居中有多种方式,以下是几种常见的方法:

方法 1:使用 Flexbox

.container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;     /* 垂直居中 */
  height: 100vh;           /* 容器高度为视口高度 */
}

方法 2:使用 Grid

.container {
  display: grid;
  place-items: center; /* 水平和垂直居中 */
  height: 100vh;
}

方法 3:使用 绝对定位 + transform

.container {
  position: relative;
  height: 100vh;
}

.center-element {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

2. 左侧固定宽度,右侧自适应

这种布局通常用于侧边栏和内容区域的布局。

方法 1:使用 Flexbox

.container {
  display: flex;
}

.left {
  width: 200px; /* 左侧固定宽度 */
}

.right {
  flex: 1; /* 右侧自适应 */
}

方法 2:使用 Grid

.container {
  display: grid;
  grid-template-columns: 200px 1fr; /* 左侧固定宽度,右侧自适应 */
}

方法 3:使用 浮动 + margin

.left {
  float: left;
  width: 200px; /* 左侧固定宽度 */
}

.right {
  margin-left: 200px; /* 右侧自适应 */
}

3. 三列均分布局

三列均分布局通常用于展示内容、侧边栏等场景。

方法 1:使用 Flexbox

.container {
  display: flex;
}

.column {
  flex: 1; /* 三列均分 */
  margin: 0 10px; /* 可选:列间距 */
}

方法 2:使用 Grid

.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr; /* 三列均分 */
  gap: 10px; /* 列间距 */
}

方法 3:使用 浮动 + 百分比宽度

.column {
  float: left;
  width: 33.33%; /* 三列均分 */
  box-sizing: border-box; /* 防止 padding 和 border 影响宽度 */
}

4. 综合示例

以下是一个综合示例,包含水平垂直居中、左侧固定右侧自适应、三列均分布局:

<div class="container">
  <!-- 水平垂直居中 -->
  <div class="center-box">居中内容</div>

  <!-- 左侧固定,右侧自适应 -->
  <div class="layout">
    <div class="left">左侧固定宽度</div>
    <div class="right">右侧自适应</div>
  </div>

  <!-- 三列均分布局 -->
  <div class="three-columns">
    <div class="column">第一列</div>
    <div class="column">第二列</div>
    <div class="column">第三列</div>
  </div>
</div>
/* 水平垂直居中 */
.center-box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  background-color: lightblue;
}

/* 左侧固定,右侧自适应 */
.layout {
  display: flex;
  margin-top: 20px;
}

.left {
  width: 200px;
  background-color: lightcoral;
}

.right {
  flex: 1;
  background-color: lightgreen;
}

/* 三列均分布局 */
.three-columns {
  display: flex;
  margin-top: 20px;
}

.column {
  flex: 1;
  margin: 0 10px;
  background-color: lightyellow;
  text-align: center;
  padding: 10px;
  box-sizing: border-box;
}

总结

  • 水平垂直居中:推荐使用 FlexboxGrid,简单高效。
  • 左侧固定右侧自适应:推荐使用 FlexboxGrid,代码简洁。
  • 三列均分布局:推荐使用 FlexboxGrid,易于维护。