flex计算时会减去内部盒子的padding值再去计算?
仅作好奇flex布局计算方式。
场景
flex布局里有两个盒子分别flex:1;各占50%的宽度。如果想左边盒子加个padding-left/margin-left,右边还保持宽度50%怎么写?(仅flex方式)
发现
即便设置了box-sizing属性,flex依然会除去里面盒子的padding-left值再去计算比例。
结论
只能通过再去嵌套一层盒子去实现。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
/* 不建议这么写哦,不要学我哦 */
* {
box-sizing: border-box;
}
.box {
width: 100%;
height: 500px;
background-color: skyblue;
display: flex;
}
.box1 {
background-color: lightgreen;
flex: 1;
}
.box2 {
background-color: pink;
flex: 1;
}
/*
.fhf{
padding-left:50px;
width:100%;
height:100%;
}
*/
</style>
</head>
<body>
<div class="box">
<div class="box1">
<!-- <div class="fhf"></div> -->
</div>
<div class="box2"></div>
</div>
</body>
</html>
提问
为什么呢?什么原理?评论区蹲一个大佬。
最佳实现:基于flex-basis
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
* {
box-sizing: border-box;
}
.box {
width: 100%;
height: 500px;
background-color: skyblue;
display: flex;
}
.box1 {
background-color: lightgreen;
flex: 1;
margin:50px;
padding-left:50px;
}
.box2 {
background-color: pink;
flex: 0 0 50%;
}
/*
.fhf{
padding-left:50px;
width:100%;
height:100%;
}
*/
</style>
</head>
<body>
<div class="box">
<div class="box1">
<!-- <div class="fhf"></div> -->
</div>
<div class="box2"></div>
</div>
</body>
</html>