Calculate a relative value based on absolute values

61 Views Asked by At

I'm building a page and, in other to make it responsive, I'm trying to adjust some values based on the viewport width.

In particular, I have a DIV that I want to split in 2 columns. I'd like those columns to be 50% each for small screens (min 670px) and 40%/60% for bigger screens (max 1280px). To make matters worse, this DIV also has a variable margin also depending on the viewport size. Take a look at the diagram:

<--------viewport-------->
+------+----------+------+
|      |          |      |
|      |          |      |
|      |          |      |
|      |          |      |
|      |          |      |
+------+----------+------+
       <---div---->
<------>          <------>
variable          variable
 margin            margin

I'm trying to pull this off with this CSS declaration (among other properties, of course):

div {
   display: grid;
   grid-template-rows: 1fr;
   grid-template-columns: clamp(40%, 50% - 10% * (100vw - 670px) / 610px, 50%) clamp(50%, 50% + 10% * (100vw - 670px) / 610px, 60%);
}

Note: the clamp functions are used to enforce the 670px to 1280px range.

This, however, renders the first column with a 100% width and the second one with 0%. Upon inspection on firefox, it highlights this property as invalid (which explains the clear renderization problem).

I suspect the problem is in the (100vw - 670px) / 610px as this will, most likely, yield a value with a unit despite what I need is a unitless value.

How could I get this working?

1

There are 1 best solutions below

1
Maziar Rumiani On

I have a solution with flex.

Also for the margin you could give the container padding instead with any unit you want:

.container{
  width:100%;
  padding:10px;
  box-sizing:border-box;
}
.parent{
  display:flex;
  max-width:1280px;
  width:100%;
}
.first{
  width:40%;
  height:200px;
  background:red;
}
.second{
  width:60%;
  height:200px;
  background:blue; 
}
@media(max-width:700px){
  .first{
  width:50%;
  background:red;
}
.second{
  width:50%;
  background:blue; 
}
}
<div class='container'>
  <div class='parent'>
    <div class='first'>first</div>
    <div class='second'>second</div>
  </div>
</div>