对齐内容使网格项占用更少的空间

时间:2018-05-26 15:42:01

标签: html css css3 css-grid

我正在尝试CSS网格布局。代码如下。



.navbar{
    display: grid;
    background: #000;
    grid-template-columns: 3fr 1fr;
}

.brand{
    justify-self: start;
    padding: 1em;
    font-weight: 800;
    font-style: 1.2em;
}

.items{
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template: 1fr auto;
}

.navbar li{
    padding: 1em;
    list-style-type: none;
}

.navbar a{
    color: white;
    text-transform: uppercase;
    text-decoration: none;
}

.navbar li:hover{
    background: white;
}

.navbar li:hover>a{
    color: black;
}

<html>
    <head>
        <title>The Blog</title>
        <link rel="stylesheet" href="index.css">
    </head>
    <body>
        <nav class = "navbar">
            <li class="brand"><a href="#">The Blog</a></li>
            <div class="items">
                <li><a href="#">Sign In</a></li>
                <li><a href="#">FAQ</a></li>
                <li><a href="#">About</a></li>
            </div>
        </nav>
    </body>
    </html>
&#13;
&#13;
&#13;

现在,我希望。<li>网格中的所有items元素都居中,但也占据网格列的整个宽度和高度,这样当我将鼠标悬停在它们上方时,整列会发生变化背景颜色。现在我使用jusify-itemsalign-items进行定位,但这会使悬停部分搞砸。如何解决它的想法?

2 个答案:

答案 0 :(得分:1)

.navbar {
  display: grid;
  background: #000;
  grid-template-columns: 1fr 1fr;
}

.brand {
  justify-self: start;
  padding: 1em;
  font-weight: 800;
  font-size: 1.2em;
}

.items {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

a {
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  text-transform: uppercase;
  text-decoration: none;
}

.navbar a:hover {
  background: white;
  color: black;
}
<nav class="navbar">
  <a class="brand" href="#">The Blog</a>
  <div class="items">
    <a href="#">Sign In</a>
    <a href="#">FAQ</a>
    <a href="#">About</a>
  </div>
</nav>

更多信息:Centering in CSS Grid

答案 1 :(得分:0)

我没有使用网格,但我使用flex。

下面的代码是我测试过的,似乎是你的原始代码发布的工作,除了它填充了导航栏的其余部分(假设这是你想要的)

 .navbar{ 
display: flex; //this is the first layout
background: #000;
}

.brand{
padding: 1em;
font-weight: 800;
font-style: 1.2em;
background-color: green;
}

.items{
display: flex;  //this must not change as it makes sure all items can use the flexbox grid
flex: 1; //this makes it take remaining space after the brand is used
}

.navbar li{
display:flex; //this can be changed as there are no sub items requiring the flexbox grid
padding: 1em;
list-style-type: none;
}

.items li {
flex: 1; //sets each items li to be evenly spaced
}

.navbar a{
color: white;
text-transform: uppercase;
text-decoration: none;
}

.navbar li:hover{
background: white;
}

.navbar li:hover>a{
color: black;
}