Daiaiai
Daiaiai

Reputation: 1089

Recalculate percentage in pixel live?

I have a fluid percentage-based horizontal grid for my project and like to use the very same vertical margins as my horizontal ones.

So I have something like this:

.block_12_24{
display:inline-block;
vertical-align:top;
width:48%;
margin-right:2%;
margin-left:0;
/* Now this is what I need to have the very same as the margin-right-value: */
margin-top: 17px; //instead of that
}

And now I'd like to have the same values for margin-top as for margin-right. My guess is, that I need to recalculate the 2% into an absolute amount like px and assign that value to margin-top. It's not that important to be checking it all the time, just once initially. Would JavaScript be the only possibility by doing it so:

  1. giving the margin-top a roughly fitting value like 17px
  2. Letting the page load
  3. Checking the browsers width in px via JavaScript
  4. var margin= that_amount/50;
  5. Manipulating the margin-top of .block_12_24 into that amount

Or could I also do that solely in CSS? Thanks

Upvotes: 1

Views: 61

Answers (1)

smnbbrv
smnbbrv

Reputation: 24581

If you always make the margin on the window-size base (your document is not horizontally scrollable) you can use viewport percentage values vw instead of usual percentage:

margin: 2vw;

This will set margin for all sides based on the width.

The support of this method across all browsers is quite good.

Upvotes: 1

Related Questions