简体   繁体   中英

How do I build a responsive navigation menu within a grid container?

I have a simple navigation

<nav>
  <ul>
    <li><a href="">Home</a></li>
    <li><a href="">About</a></li>
    <li><a href="">Contact</a></li>
  </ul>
</nav>

that I want to be responsive where the links resize (horizontally) based on user device. This nav rests comfortably within a sub-grid container of a grid-container ( .class {display: subgrid;} not used as its buggy).

CSS for the grid-container is as follows:

.container {
  grid-template-areas:
  "header header header header"
  "nav nav nav nav"
  "main main main main"
  "footer footer footer footer"
}

CSS for the subgrid (nav) container is as follows:

.ul {
  display: grid;
  grid-template-areas: "home about contact";
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: 25%;
  list-style-type: none;
  margin: 0;
  padding: 0;
}

The grid-template-areas are declared accordingly:

.home {grid-area: home;}
.about {grid-area: about};
.contact {grid-area: contact};

I have tinkered with this, particularly the grid-template-areas , for sometime now without progress. I am not sure if I should scrap the subgrid container altogether or if there is a simple step that I am overlooking.

Any assistance would be appreciated!

Using CSS Grid for the overall layout makes sense.

Using CSS Grid for a simple navigation menu, although it's workable, may be overkill. There's a simpler way to achieve the goal: Flexbox.

Make your nav grid item also a flex container:

 nav { display: flex; height: 50px; /* non-essential; for demo only */ } /* non-essential; for demo only */ a { flex: 1; border: 1px solid gray; background-color: lightgray; display: flex; align-items: center; justify-content: center; text-decoration: none; } 
 <nav> <a href="">Home</a> <a href="">About</a> <a href="">Contact</a> </nav> 

For example, you the following html navbar:

<nav class="nav-menu">
   <a>Item 1</a>
   <a>Item 2</a>
   <a>Item 3</a>
</nav>

You could use a rule to set a different width

.nav-menu {
   display: flex;

   a {
      width: 25px;
   }
}

@media screen and (max-width: 500px) {
   .nav-menu a {
      width: 20px;
   }
}

The new width inside @media will replace what was assigned before if the screen size is bigger than 500px.

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