Search code examples
htmlcsscss-gridgrid-layoutdisplay

Unwanted space between rows (html grid)


Same problem as here: HTML divs grid - unwanted space between rows. I think it's still unsolved.

I am new to HTML (following FreeCodeCamp curriculum) and I'm trying to create my first webpage.

I would like to arrange the elements using grid display, but I don't seem to understand its behavior. I don't understand why is there blank space between my rows (title and subtitle) -marked in red-.

Undesired white space between rows

Without any extra CSS, I would expect my h1 to start at the top of the grid, then my id="subtitle" to be sticked after it. Then with some CSS I could add the desired space in between.

* {
  box-sizing: border-box;
  border: 1px solid black;
}

body {
  background-color: #fff;
}

header {
  font-family: gotu;
}

.grid-header {
  display: grid;
  justify-items: center;
}

h1 {
  font-size: 8vw;
  font-weight: bold;
}

#subtitle {
  font-size: 3vw;
}
<header class="grid-header" id="title">
  <h1>Hayao Miyazaki</h1>
  <p id="subtitle">Father of two sons and modern anime.</p>
</header>

Thank you so much in advance! :-)

Gerard


Solution

  • The reason of the white space is not a fault with the CSS grid specification, but because you've got margins on the <h1> and <p> elements that are present in the browser's default stylesheet. If you inspect the element in your browser's dev tools, you will see that your user agent default stylesheet has applied margins to these elements.

    Resetting margins to 0 using margin: 0 will fix your problem. This is also a reason why CSS resets are pretty much in every single boilerplate you come across: to remove opiniated browser-specific default styles.

    * {
      box-sizing: border-box;
      border: 1px solid black;
    }
    
    body {
      background-color: #fff;
    }
    
    header {
      font-family: gotu;
    }
    
    .grid-header {
      display: grid;
      justify-items: center;
    }
    
    h1 {
      font-size: 8vw;
      font-weight: bold;
      margin: 0;
    }
    
    #subtitle {
      font-size: 3vw;
      margin: 0;
    }
    <header class="grid-header" id="title">
      <h1>Hayao Miyazaki</h1>
      <p id="subtitle">Father of two sons and modern anime.</p>
    </header>