小技巧:
实现如图 子元素自动居于右下角
.container {
display: flex;
flex-direction: row;
background: pink;
}
.child {
background: black;
width: 50px;
height: 50px;
margin-left: auto;
align-self: flex-end;
}
<div class="container">
<div class="child"></div>
</div>
bug:
1. 子元素flex 均为1 时 其中一个如果设置了padding 那么会出现padding 元素多分空间问题 如图
<style>
.container {
width: 300px;
height: 50px;
display: flex;
flex-direction: row;
}
.child {
flex: 1;
border:1px solid black;
}
.child2 {
padding: 0 40px;
}
</style>
<div class="container">
<div class="child"></div>
<div class="child child2"></div>
<div class="child"></div>
</div>
解决方法: 给所有均分 元素添加 flex-basis: calc(100% / n);
box-sizing: border-box;两个属性
<style>
.container {
width: 300px;
height: 50px;
display: flex;
flex-direction: row;
}
.child {
flex: 1;
flex-basis: calc(100% / 3); //解决padding问题
box-sizing: border-box ; //解决padding问题
border:1px solid black;
}
.child2 {
padding: 0 40px;
}
</style>
<div class="container">
<div class="child"></div>
<div class="child child2"></div>
<div class="child"></div>
</div>
如果是想按照1:2:3 分布 且每个child 都有padding可以这样
<style>
.container {
width: 600px;
height: 50px;
display: flex;
flex-direction: row;
}
.child {
box-sizing: border-box;
border: 1px solid black;
}
.child1 {
flex-basis: calc(100% / 6);
}
.child2 {
padding: 0 40px;
flex-basis: calc(200% / 6);
}
.child3 {
/*flex: 3;*/
padding: 0 40px;
flex-basis: calc(300% / 6);
}
</style>
<div class="container">
<div class="child"></div>
<div class="child child2"></div>
<div class="child"></div>
</div>
或者样式改为width
<style>
.container {
width: 600px;
height: 50px;
display: flex;
flex-direction: row;
}
.child {
box-sizing: border-box;
border: 1px solid black;
}
.child1 {
padding: 0 40px;
width: calc(100% / 6);
}
.child2 {
padding: 0 40px;
width: calc(200% / 6);
}
.child3 {
padding: 0 40px;
width: calc(300% / 6);
}
</style>
flex 子元素为auto时 出现高度溢出压缩其他元素空间的问题
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>flex</title>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.container {
width: 60px;
height: 500px;
display: flex;
flex-direction: column;
}
.child1 {
height:100px;
background: yellow;
}
.child2 {
flex: auto;
background: red;
overflow: scroll;
height: 0;// 添加heigh:0 可解决此问题
}
.child3 {
width: 100%;
height:100px;
background: blue;
}
.overChild{
height:320px
}
</style>
</head>
<body>
<div class="container">
<div class="child child1"></div>
<div class="child child2">
<div class="overChild"></div>
</div>
<div class="child child3"></div>
</div>
</body>
</html>
如果父级元素 flex-direction :row 时 设置auto 元素 width :0 即可