Search code examples
htmlcsscss-grid

Grid setup in CSS?


I am new to CSS and HTML and have a setup of divs in CSS, something like this:

#topBar {
  margin-top: 0;
  height: 100px;
  width: 100%
}

#sideBar {
  width: 50px;
  margin-left: 0;
  margin-top: 100px;
  height: 100%;
}

#main {
  margin-left: 50px;
  margin-top: 100px;
  margin-bottom: 50px;
}

#footer {
  margin-bottom: 0;
  width: 100%;
}
<div id="container">
  <div id="topbar" />
  <div id="sidebar" />
  <div id="main" />
  <div id="footer" />
</div>

But that does not look anything like how I want it. It leaves space for every div, even though their space is restricted to x width and x height.

How could I set up divs to look as desired? Ie have a footer, main, sidebar, and topbar in CSS?


Solution

  • CSS actually has built in grid "builder" that you can use. I was doing something similar not long ago and ended up doing it like this:

    #container {
        display: grid; //uses grid
        height: 100vh; // vh and vw is percentages of the screens width and height, nice for scaling for different devices
        width: 100vw;
        grid-template-columns: 1fr 9fr; // sets how big columns are, this sets the column quantity to two, and the first one gets 1 fraction of the are, and column two gets 9 fractions. 1fr is for sidebar
        grid-template-rows: 1.5fr 15fr 3fr; // Same as with column, but this includes footer, so 1.5 fraction goes to top bar, 15 fractions to sidebar and main area, and 3 fractions to footer
        grid-template-areas:
        "header header" // sets area to use, the same area given space in above lines. They can be directly referenced in other parts of the css documents.
        "navbar main"
        "footer footer";
    }
    
    #topbar {
        grid-area: header; // Referencing previous made areas
        display: flex; // I used this to make the top bar, as this would align the items in the bar horizontally with same amount of space between
        justify-content: space-between;
        align-items: center; //used this to center items vertically
    }
    
    #sidebar {
        grid-area: sidebar;
        text-align: center; // used this to align the text center horizontally
    }
    
    #main {
        grid-area: main;
    }
    
    #footer {
        grid-area: footer;
    }