CSS: Is it possible to make a div become wider as the screen width becomes smaller?

让人想犯罪 __ 提交于 2021-02-16 17:56:45

问题


I want to try to size a div width as an inverse of the screen size, until it hits a maximum of 100%, using only CSS (no JS please).

To be clear, here is an example:

  • if the screen size is 500px wide the div width would be 100%
  • if the screen size is 1000px wide the div would be 50%
  • and so on

I don't want to use media queries because its just too much micromanaging, im hoping for some kind of proportional calc() way of doing this

So far I've been proportionally sizing div widths using 'vw' dimensions which works just fine, but in this case I want to try to do the inverse.

I'm hoping someone has come up with a piece of magic methodology to do this?


回答1:


You can use calc(Xpx - Yvw). The Yvw will grow when the screen is big making the div smaller and the opposite.

Here is a basic example:

.box {
  width:calc(750px - 50vw);
  min-width:50px; /* let's have a minimum boundary */
  max-width:100%; /* and a maximum boundary */
  margin:auto;
  height:50px;
  background:red;
}
<div class="box"></div>

But as I commented, having a div with a fixed size will also do the job visually

.box {
  width:500px;
  max-width:100%;
  margin:auto;
  height:50px;
  background:red;
}
<div class="box"></div>


来源:https://stackoverflow.com/questions/63428254/css-is-it-possible-to-make-a-div-become-wider-as-the-screen-width-becomes-small

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!