命名网格线有什么好处?

时间:2018-07-12 23:01:10

标签: css css3 grid css-grid

在CSS网格布局中命名网格线有什么好处?我已经看到许多这样做的例子,我想知道这样做有什么好处?为什么不仅仅依靠行号,而不是例如first-column-start

2 个答案:

答案 0 :(得分:1)

简短回答

命名的网格线使代码更易于理解和维护。


说明

网格线是网格的水平和垂直分隔线。

在两条平行的网格线之间形成一列或一行。

网格线是由相交的网格线组成的。

enter image description here

来源:W3C CSS Grid Specification

block axis / inline axis definitions

可以以数字定义的名称引用网格线。以下两个规则相同。

#grid-container {
    grid-template-rows: 2em 1fr 3em;
}

#grid-container {
    grid-template-rows: [header-start] 2em [header-end body-start] 1fr [body-end footer-start] 3em [footer-end];
}

请注意,行可以有多个名称。

在布置网格时,我们可以只使用数字值,如下所示:

#grid-item-1 { grid-row: 1 / 2; } /* the header */

#grid-item-2 { grid-row: 2 / 3; } /* the content */

#grid-item-3 { grid-row: 3 / 4; } /* the footer */

或者,为了使事情更易于理解和维护(例如,一年后再回到此代码,或将此代码传递给其他开发人员),请改用有意义的名称:

#grid-item-1 { grid-row: header-start / header-end; }

#grid-item-2 { grid-row: body-start / body-end; }

#grid-item-3 { grid-row: footer-start / footer-end; }

代码示例:

article {
  display: grid;
  grid-template-rows: [header-start] 2em [header-end body-start] 1fr [body-end footer-start] 3em [footer-end]; }

}
section:nth-child(1) { grid-row: header-start / header-end; }

section:nth-child(2) { grid-row: body-start / body-end; }

section:nth-child(3) { grid-row: footer-start / footer-end;}

/* non-essential demo styles */
article {
  grid-gap: 1px;
  background-color: gray;
  height: 100vh;
  border: 1px solid gray;
}
section {
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: center;
}
section:nth-child(1) { background-color: aqua; }
section:nth-child(2) { background-color: orange; }
section:nth-child(3) { background-color: lightgreen; }
body                 { margin: 0;}
*                    { box-sizing: border-box; }
<article>
  <section>header</section>
  <section>body</section>
  <section>footer</section>
</article>

更多信息:https://www.w3.org/TR/css3-grid-layout/#named-lines

答案 1 :(得分:0)

好的定义

  

命名网格线使您可以钩住网格,在网格中可以附加内容。

https://gedd.ski/post/naming-css-grid-lines/