skip to Main Content

I’ve encountered an issue with CSS Grid and nesting, and I’m hoping someone can help clarify the differences for me. Here are the two sets of CSS I’m working with:

First CSS and Result:

.menu-vertical {
  display: grid;
  gap: 16px;
  align-content: start;

  & a {
    padding: 8px 12px;
    border-radius: 8px;

    &.current {
      background-color: darkgrey;
    }
    &.hover {
      background-color: darkkhaki;
    }
  }
  .with-icon-vertical {
    display: grid;
    justify-items: center;
    font-size: 12px;
  }
}

enter image description here

Second CSS and Result:

.menu-vertical {
  display: grid;
  gap: 16px;
  align-content: start;

  & a {
    padding: 8px 12px;
    border-radius: 8px;

    &.current {
      background-color: darkgrey;
    }
    &.hover {
      background-color: darkkhaki;
    }
  }
}

.with-icon-vertical {
  display: grid;
  justify-items: center;
  font-size: 12px;
}

enter image description here

HTML:

<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <link rel="stylesheet" href="../assets/reset.css" />
        <link rel="stylesheet" href="../assets/base.css" />
        <link rel="stylesheet" href="style.css" />
        <link href="https://use.fontawesome.com/releases/v6.2.0/css/all.css" rel="stylesheet">
    </head>
    <body class="padding-small">
        <ul class="menu-vertical">
            <li><a href="" class="fa-solid fa-house   with-icon-vertical">Home</a></li>
            <li><a href="" class="fa-solid fa-map  with-icon-vertical current">Map</a></li>
            <li><a href="" class="fa-solid fa-location-dot  with-icon-vertical">Location</a></li>
            <li><a href="" class="fa-solid fa-heart with-icon-vertical">Reputation</a></li>
        </ul>
    </body>
</html>

The display of my HTML is completely different with these two CSS setups. Can someone explain why this is happening?

2

Answers


  1. It’s a specificity issue. Font awesome apply a display property to .fa-solid and only your first code is more specific because it will resolve to .menu-vertical .with-icon-vertical

    In the second case, it’s only .with-icon-vertical.

    To make both code behave the same, make sure your style.css is placed after the font-awesome CSS

    <link href="https://use.fontawesome.com/releases/v6.2.0/css/all.css" rel="stylesheet">
    <link rel="stylesheet" href="style.css" />
    
    Login or Signup to reply.
  2. Without nesting, .with-icon-vertical is not within any containers so it works more flexibly to change its position or add it to any place that requires this block;

    With nesting, it works within a container, which can be seen as part of a block/context, and it allows for easier management and styling within that container.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search