Flex布局通过容器和项目的属性配合实现灵活的排版效果,使用JavaScript动态修改这些属性可以满足交互场景下的布局变化需求,比如按钮点击切换排列方式、窗口 resize 时调整对齐方式等。

Flex布局属性分类
要动态修改Flex布局属性,首先需要明确属性属于容器还是项目:
- Flex容器属性:作用于设置了
display: flex的父元素,比如flex-direction、justify-content、align-items等 - Flex项目属性:作用于容器内部的子元素,比如
flex-grow、flex-shrink、align-self等
动态修改Flex容器属性
修改容器属性直接操作容器元素的style对象即可,以下是常见容器属性的修改示例:
// 获取Flex容器元素
const flexContainer = document.getElementById('flex-container');
// 修改排列方向为垂直排列
flexContainer.style.flexDirection = 'column';
// 修改主轴对齐方式为两端对齐
flexContainer.style.justifyContent = 'space-between';
// 修改交叉轴对齐方式为居中对齐
flexContainer.style.alignItems = 'center';
// 修改是否换行
flexContainer.style.flexWrap = 'wrap';
动态修改Flex项目属性
Flex项目的属性修改方式和容器类似,只是操作对象是容器内部的子元素:
// 获取第一个Flex项目元素
const firstFlexItem = document.querySelector('#flex-container .item:first-child');
// 修改项目的放大比例
firstFlexItem.style.flexGrow = '2';
// 修改项目的缩小比例
firstFlexItem.style.flexShrink = '0';
// 修改项目自身的交叉轴对齐方式
firstFlexItem.style.alignSelf = 'flex-end';
// 修改项目的排列顺序
firstFlexItem.style.order = '3';
完整示例:点击按钮切换布局
以下是一个可交互的完整示例,点击不同按钮可以动态切换Flex容器的排列方向和对齐方式:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>动态修改Flex布局示例</title>
<style>
#flex-container {
display: flex;
width: 100%;
height: 200px;
background-color: #f0f0f0;
padding: 10px;
}
.item {
width: 80px;
height: 80px;
background-color: #4CAF50;
color: white;
display: flex;
align-items: center;
justify-content: center;
margin: 5px;
}
.btn-group {
margin-top: 20px;
}
button {
margin-right: 10px;
padding: 8px 16px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="flex-container">
<div class="item">项目1</div>
<div class="item">项目2</div>
<div class="item">项目3</div>
</div>
<div class="btn-group">
<button onclick="changeDirection('row')">水平排列</button>
<button onclick="changeDirection('column')">垂直排列</button>
<button onclick="changeJustify('flex-start')">左对齐</button>
<button onclick="changeJustify('center')">居中对齐</button>
<button onclick="changeJustify('space-between')">两端对齐</button>
</div>
<script>
const container = document.getElementById('flex-container');
function changeDirection(direction) {
container.style.flexDirection = direction;
}
function changeJustify(justifyValue) {
container.style.justifyContent = justifyValue;
}
</script>
</body>
</html>
注意事项
- 修改属性时属性名使用驼峰命名法,比如
flex-direction对应flexDirection,justify-content对应justifyContent - 如果样式是通过CSS类定义的,也可以通过修改元素的
className或者classList来切换布局,比直接修改style更便于维护 - 动态修改属性后,浏览器会自动重新计算布局,不需要手动触发重排
JavaScriptFlex布局flex_containerflex_item动态修改属性修改时间:2026-07-24 11:54:31