locked
What's the HTML/CSS equivalent to XAML Grid

    Question

  • One thing I like about Grid is that it automatically expands to take up the entire space it's given (unless you constrain it). I can't find the equivalent in HTML/CSS. I've tried using just div and using flexbox and html grid, but all of their sizing requires pixel or percentages.

    What' I'm looking to do is create a grid that has a XAML margin of 120,50,0,50 that automatically calculated it's height and width. Using HTML, I'd get a 0 height element that had those margins. If I set the element to 100% for height, then I'd have a box that is offset by 120,50 as if the bottom and right margins were ignored.

    I want my layout to be as flexible as possible to accommodate all screen sizes but I want to maintain the fixed margins around the content.

    Friday, October 21, 2011 2:15 PM

All replies

  • The CSS grid allows you to specify rows/columns in terms of pixels, percentages, or "fractions" where the latter will fill in the remaining space. To have a grid that fills the whole screen, but then has the margins you indicate, you'd style it as follows, where nfr is the syntax for relative fractions:

    #myDiv {
        width: 100%;
        height: 100%;
        display: -ms-grid;
        -ms-grid-rows: 50px 1fr 50px; /* 50px on top and bottom */
        -ms-grid-columns: 120px 1fr; /* 120px on left, 0 on right */
    }
    
    

    This way, grid cell (2, 2) [CSS grid is 1-based]  will stretch to fill whatever screen space remains after taking off 50px on top and bottom and 120px on the left.

    You could then, if you wanted, place a child div inside that cell, and use -ms-grid again to divide it up further. For example:

    <body>
        <div id="myDiv">
            <div id="childDiv">
            </div>
        </div>
    </body>
    
    
    /* In CSS */
    #childDiv {
        /* Place this element in cell (2,2) of parent grid
        -ms-grid-row: 2;
        -ms-grid-column: 2;
    
        /* Define this element's layout as a grid as well */
        display: -ms-grid;
        -ms-grid-rows: 1fr 3fr 5fr 1fr;
        -ms-grid-columns: 3fr 1fr 50px;
    }
    

    Here, that child div would contain three columns, the rightmost of which is fixed (50px) and the other two occupying 75% and 25% of the remaining space (the relative amounts between 3fr and 1fr which add up to 4 fractions, so they're 3/4ths and 1/4th). It then also has four rows that are sized to 10%, 30%, 50%, and 10% (and we could just use %'s here since there's no intermix of other units).

    Hope that answers the question.

    .Kraig

    Friday, October 21, 2011 7:03 PM