flex常用固定搭配
flex简写:flex-grow(项目放大),flex-shrink (项目缩小),flex-basis(项目本身)
- flex: 1;
全写:flex: 1 1 0%;内容自动放大或缩小占满剩余空间,优先最小的。
1、子元素都设置flex: 1; 子元素盒子会平分并占满父盒子,使用场景:每个子元素有相同的宽度,平分整个可用空间;
.parent {
display: flex;
}
.son{
flex:1;
}
2、一个元素宽度(或高度)固定,另一个元素宽度(或高度)自适应。
.parent {
display: flex;
}
.son1 {
width: 200px; //或者 height: 200px;
}
.son2 {
flex: 1; // flex: 1 1 0%;
}
- flex:auto
全写:flex: 1 1 auto;
使用场景:
子元素根据内容自适应宽度。
对比区别
flex:1 的元素:宽度固定,即使内容很短,也要按比例;
flex:auto 的元素:优先 “撑满” 自身内容所需的宽度,剩余空间再按比例分配,体现“auto”。
- flex实现每行放置具体数目,并且只有中间有间距,两边没有间距(下面例子实现每行排4个)
方法1:
<template>
<div class="box">
<div class="f" v-for="item of list">
{{item}}
</div>
</div>
</template>
<script lang="ts" setup>
const list = [1,2,3,4,5,6,7,8,9]
</script>
<style scss>
.box {
width: 100%;
display: flex;
flex-wrap: wrap;
background-color: yellow;
gap: 10px 0; /* gap是子元素之间的间距,10px是上下距离,0是左右距离 */
}
.f {
background-color: pink;
width: calc((100% - 30px)/4); /* 每个子元素之间距离等于100%-3个空隙10px,除以4 */
box-sizing: border-box;
margin-right: 10px;
}
/* 移除每行第4个子元素的右边间隙 */
.f:nth-child(4n) {
margin-right: 0px;
}
</style>
效果图

方法2:
#test {
width: 600px;
height: 200px;
display: flex;
flex-wrap: wrap;
// 直接用gap,但是gap在有的地方不兼容,用@supports not处理
gap: 10px;
}
#test>div{
width: 20%;
flex-grow: 1;
border: 1px solid green;
background-color: pink;
}
/* 回退:不支持 gap 的浏览器 */
@supports not (gap: 10px) {
#test {
display: flex;
flex-wrap: wrap;
margin: -10px -10px 0 0; /* 抵消子元素的 margin:去除第一行的子元素的边距 */
}
#test > div {
margin: 0 10px 10px 0;
}
}
- flex结合margin-left:auto,实现有的元素在最左边,有的元素在最右边。
margin-left:auto,把元素推到最右边。
<template>
<div class="box">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
</div>
</template>
<script lang="ts" setup>
</script>
<style scss>
.box {
width: 100%;
background-color: bisque;
display: flex;
text-align: center;
>div{
width: 40px;
line-height: 32px;
background-color: lawngreen;
}
.div2{
margin-left: 10px;
}
.div3{
margin-left: auto;
}
}
</style>
效果图


3365

被折叠的 条评论
为什么被折叠?



