使用 CSS,当容器从 1000px 缩小到 600px 时,如何平滑地将 div 的宽度从容器的 80% 更改为容器的 100%?

Cod*_*key 5 css

当宽度为 1000px 或更大时,我希望 div 为其容器宽度的 80%。

当宽度为 600px 或更小时,我希望它是容器宽度的 100%。

在中间,我希望它在中间。

http://jsfiddle.net/ayjtr1q4/9/

div {
  background: #def;
  height: 100px;
  margin: 0 auto;
}

@media screen and (min-width: 1000px) {
  div {
    width: 80%
  }
}

@media screen and (min-width: 601px) and (max-width: 999px) {
  div {
    /* what goes in here? */
  }
}

@media screen and (max-width: 600px) {
  div {
    width: 100%
  }
}
Run Code Online (Sandbox Code Playgroud)
<div>
  As you resize the screen this snaps from 80% to 100%. I'd like to achieve a smooth transition between the two instead, so that if you set it to 800px wide you'll end up with a div that's 90% of that, i.e. 720px.
</div>
Run Code Online (Sandbox Code Playgroud)

ContainerSize -> divSizeAs% (divSizeInPixels)

  • 400 像素 -> 100% (400 像素)
  • 500 像素 -> 100% (500 像素)
  • 600 像素 -> 100% (600 像素)
  • 700 像素 -> 95% (665 像素)
  • 800 像素 -> 90% (720 像素)
  • 900 像素 -> 85% (765 像素)
  • 1000 像素 -> 80% (800 像素)
  • 1100 像素 -> 80% (880 像素)
  • 1200 像素 -> 80% (960 像素)

ETC。

我知道我可以设置十几个带断点的媒体查询,但如果可能的话,我希望这是一个平稳的过渡。

我觉得我可以用 做一些聪明的事情calc,但我有点空白,无法完全理解什么!但我猜你需要一些最大/最小功能,我不相信 CSS 有这些功能?

到目前为止,我提出的中间立场是 3 个媒体查询。一个用于 >= 1000px ( width:800%),一个用于 <= 600px ( width:100%),一个用于中间......但即便如此,我也无法弄清楚中间地带的规则应该是什么?

off*_*ite 3

你可以用 Calc 来做到这一点。您只关心超过 600 像素 (100% - 600 像素) 的空间量,增量是要平滑的总空间 (400 像素)。我不是一个真正的数学家,也许其他人(更聪明的)可以给你一个更好的方程。

@media screen and (min-width:1000px) and (max-width:600px){
  #container{
    width: calc(100% - ((100% - 600px) * 0.466));
  }
}
Run Code Online (Sandbox Code Playgroud)

完整代码片段:

@media screen and (min-width:1000px) and (max-width:600px){
  #container{
    width: calc(100% - ((100% - 600px) * 0.466));
  }
}
Run Code Online (Sandbox Code Playgroud)
#container{
  background: red;
  width: 800px;
  height: 20px;
}  

@media screen and (max-width:600px){
  #container{
    width: 100%;
  }
}

@media screen and (max-width: 1000px) and (min-width: 600px) {
  #container{
    background: green;
    width: calc(100% - ((100% - 600px) * 0.466));
  }
}
Run Code Online (Sandbox Code Playgroud)