发布于 2026-01-06 0 阅读
0

CSS Flexbox 五分钟速成 DEV 全球展示挑战赛,由 Mux 呈现:展示你的项目!

5分钟学会CSS Flexbox

由 Mux 赞助的 DEV 全球展示挑战赛:展示你的项目!

什么是 CSS Flexbox

CSS Flexbox 是一个一维布局模块,可用于使您的应用程序更具响应性。

Flexbox 允许您动态控制任何容器内内容的对齐方式、方向和间距。

让我们开始使用 Flexbox 吧!

复制此代码

启动代码

展示

flexbox 需要一个父容器来控制所有子元素的布局。

让我们使用显示属性

.flex-container {
  padding: 0;
  margin: 0;
  /* add display property for parent container */
  display: flex
}
Enter fullscreen mode Exit fullscreen mode

Flexbox 显示屏

弯曲方向

flex-direction 为 flex 项目建立主轴方向,可以位于行或列中。

flex-direction 默认是行方向,所以我们来尝试一下列布局方向。

.flex-container {
  padding: 0;
  margin: 0;
  /* add display property for parent container */
  display: flex;
  /* add a flex direction for items */
  flex-direction: column; 
}
Enter fullscreen mode Exit fullscreen mode

柔性方向柱

现在让我们回到行方向。

.flex-container {
  padding: 0;
  margin: 0;
  /* add display property for parent container */
  display: flex;
  /* add a flex direction for items */
  flex-direction: row; /* default */ 
}
Enter fullscreen mode Exit fullscreen mode

弯曲方向行

内容正当性

justify-content 会将所有内容沿容器的主轴方向分配空间。

justify-content 默认位于 flex-start 中

让我们试试 flex-end

.flex-container {
  padding: 0;
  margin: 0;
  /* add display property for parent container */
  display: flex
  /* add a flex direction for items */
  flex-direction: row; /* default */
  /* add content space for items */
  justify-content: flex-end;
}
Enter fullscreen mode Exit fullscreen mode

justify-content flex-end

现在我们来尝试在周围添加空格。

.flex-container {
  padding: 0;
  margin: 0;
  /* add display property for parent container */
  display: flex
  /* add a flex direction for items */
  flex-direction: row; /* default */
  /* add content space for items */
  justify-content: space-around;
}
Enter fullscreen mode Exit fullscreen mode

围绕内容空间进行合理化

响应式设计

flexbox 的一个主要优点是能够非常轻松地为大多数设备创建响应式布局。

让我们使用 flex-direction 和 CSS 媒体查询使此布局具有响应式。

.flex-container {
  padding: 0;
  margin: 0;
  /* add display property for parent container */
  display: flex;
  /* add a flex direction for items */
  flex-direction: row; /* default */
  /* add content space for items */
  justify-content: space-around;
}

/* Lets make this mobile-friendly and easy to view for screens below 767px */
@media (max-width: 767px) {
  .flex-container {
    flex-direction: column;
  }
}
Enter fullscreen mode Exit fullscreen mode

打造属于你自己的风格

最终代码

点击此处阅读更多关于Flexbox 的详细信息

这是一个关于如何使用 CSS Flexbox 的 5 分钟教程。

我们来聊聊 Flexbox 吧。

我们快速讲解了如何实现 CSS Flexbox 的网页可访问性,以及如何让你的网页项目更具响应性。如果你喜欢这篇文章,欢迎留言分享你使用 Flexbox 的想法和经验。

祝您编程愉快,
Terry Threatt

文章来源:https://dev.to/terrythreatt/css-flexbox-in-5-minutes-1fcl