问题描述
如果我有一个 body 元素并且我缩小了屏幕尺寸,它是 1:1 的比例。
如果我有一个宽度为 50% 的 body 标签。它的比例为 1:1。视口的每一个像素减少都会直接影响元素的宽度。
如果我并排放置 2 个元素。我想让第一个元素 (.left
) 从 400 像素的宽度开始,屏幕宽度为 1300 像素,但在屏幕增加到 1920 像素的过程中总共增加 100 像素。
第二个元素 (.right
) 将填充剩余的空间并按照屏幕的相应速率 +/- .left
的当前宽度减小
.right
1300px
->
1920px
400px
->
500px
.left
width:100%
我知道这行不通,但这是我目前得到的代码。
.full{
background-color: lightblue;
width:100%;
height:50px;
}
.half{
width:50%;
height:50px;
background-color:grey;
}
#flex{
display:flex;
}
.right{
max-width:500px;
min-width:400px;
height:50px;
background-color:lightgreen;
width:70%;
}
.left{
height:50px;
background-color:lightpink;
width:30%;
}
<div class="full"></div>
<div class="half"></div>
<div id="flex">
<div class="left"></div>
<div class="right"></div>
</div>
解决方法
我假设问题中的措辞是必需的,即左侧元素的最小值为 400 像素,最大值为 500 像素,并且从主体宽度 1300 像素开始的最小值开始增加大小,并且停在 1920 像素。
left 因此需要设置为具有 min-width: 400px
和 max-width: 500px
我们需要计算在给定的起始和结束主体宽度值之间增加 100 像素的宽度。这个公式是:
s + (i / d) * (a - b)
哪里 s = 左元素的起始宽度 (400) i = 左宽度增加 (100) d = 开始和结束身体宽度之间的差异 (1620) a = 现在的实际主体宽度 (100%) b = 起始主体宽度 (1300)
正确的元素是占用剩余空间所以需要给出flex: auto;
在此代码段中,使用 CSS 变量设置了各种尺寸,以便更轻松地更改它们。
.full{
background-color: lightblue;
width: 100%;
height: 50px;
}
.half{
width: 50%;
height: 50px;
background-color:grey;
}
#flex{
display: flex;
}
.right{
height: 50px;
background-color: lightgreen;
flex: auto;
}
.left{
height:50px;
background-color:lightpink;
/* SET THESE 4 VARIABLES TO WHAT YOU WANT */
--startb: 1300; /* width of the body after which left starts to get bigger */
--endb: 1920; /* width of the body after which left stops getting bigger */
--startleft: 400; /* the start (hence minimum) width of the left element */
--incw: 100; /* the increase in the left's width when have reached the end body width */
/* we calculate some interim values just to make it a bit easier to see what's happening */
--startbw: calc(var(--startb) * 1px);
--endbw: calc(var(--endb) * 1px);
--incb: calc(var(--endb) - var(--startb));
--startw: calc(var(--startleft) * 1px);
width: calc(var(--startw) + calc(calc(var(--incw) / var(--incb)) * calc(100% - var(--startbw))));
min-width: var(--startw);
max-width: calc(var(--startw) + calc(var(--incw) * 1px));
}
<div class="full"></div>
<div class="half"></div>
<div id="flex">
<div class="left"></div>
<div class="right"></div>
</div>