简体   繁体   中英

How to convert a CSS grid track from pixels to fr unit?

I want to know if possible to convert a CSS grid template track from pixels to fr. In example, I have a DIV element with 1894px of width and 200px of height with a class .grid

.grid {
    display: grid;
    width: 1894px;
    min-height: 200px;
    grid-template-columns: 1196px 100px repeat(2, 1fr);
    grid-template-rows: 1fr repeat(3, 0.5fr) 1fr;
    margin: 10px;
    gap: 0px;
}

So I want to know to how convert the value 1196px of first track of grid-template-columns to fr.

Also, what happens in case the gap is greater than 0?

In Chrome DevTools when search the expected value manually I get 1196px when changing the track value to 4fr and then check values in the Computed tab, but, how I can get this value in Javascript?

You want to have grid-template-columns: xfr 100px repeat(2, 1fr); so the formula will be:

width_container = 100px + 3*gap + (x + 2)*F With  x*F = 1196px

in your case you will have

1894px = 100px + (x + 2)*F
1794px = (x + 2)*F

we do a division and we get:

1.5 = (x + 2)/x
1.5 = 1 + 2/x
x = 4

The generic formula in your case can be written as:

(width_container - 100px - 3*gap)/1196 = 1 + 2/x
x = 2/(A/1196px - 1) where A = (width_container - 100px - 3*gap)

Below an illustration of the calculation. Note how the alt row are similar to the previous ones. Not exactly the same in some cases due to the rounding we need to do since repeat accept only integer

 $('.grid:not(.alt)').each(function() { var w = $(this).width(); var g = parseInt($(this).css('gap')); var A = w - 100 - 3*g; var x = Math.round(2/(A/1196 - 1)); $(this).next('.alt').css("grid-template-columns",x+"fr 100px repeat(2, 1fr)"); console.log(2/(A/1196 - 1) +"("+x+")"); })
 .grid { display: grid; width: 1894px; outline: 1px solid; grid-template-columns: 1196px 100px repeat(2, 1fr); margin: 10px; gap: 0px; } i { display:block; height:20px; background:red; } i:first-child { background:blue; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="grid"><i></i><i></i><i></i><i></i></div> <div class="grid alt" style=""><i></i><i></i><i></i><i></i></div> <div class="grid" style="gap:100px;"><i></i><i></i><i></i><i></i></div> <div class="grid alt" style="gap:100px;"><i></i><i></i><i></i><i></i></div> <div class="grid" style="gap:50px;"><i></i><i></i><i></i><i></i></div> <div class="grid alt" style="gap:50px;"><i></i><i></i><i></i><i></i></div> <div class="grid" style="width:1900px;"><i></i><i></i><i></i><i></i></div> <div class="grid alt" style="width:1900px;"><i></i><i></i><i></i><i></i></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM