简体   繁体   English

如何在网格容器中构建响应式导航菜单?

[英]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). 该导航器舒适地放置在网格容器的子网格容器中(.class {display:subgrid;}未用作其越野车)。

CSS for the grid-container is as follows: 网格容器的CSS如下:

.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: 子网格(nav)容器的CSS如下:

.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: grid-template-areas地声明为:

.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. 我已经对此进行了修改,尤其是grid-template-areas ,但现在没有任何进展。 I am not sure if I should scrap the subgrid container altogether or if there is a simple step that I am overlooking. 我不确定是否应该完全废弃次subgrid container或者是否有一个简单的步骤被我忽略了。

Any assistance would be appreciated! 任何援助将不胜感激!

Using CSS Grid for the overall layout makes sense. 使用CSS Grid进行整体布局很有意义。

Using CSS Grid for a simple navigation menu, although it's workable, may be overkill. 使用CSS Grid作为简单的导航菜单,虽然可行,但可能会过大。 There's a simpler way to achieve the goal: Flexbox. 有一个更简单的方法可以实现这一目标:Flexbox。

Make your nav grid item also a flex container: 使您的nav网格项目也成为弹性容器:

 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: 例如,您使用以下html导航栏:

<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. 如果屏幕尺寸大于500像素,则@media内的新宽度将替换之前分配的宽度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM