Easier way use CSS grid-template-areas to span multiple columns

拈花ヽ惹草 提交于 2019-12-11 06:37:25

问题


I really love the simplicity and ease of manipulation of grid-template-areas, but is there an easier way/shortcut to indicate an area spans multiple columns (say 12) — within the template?

This starts to get pretty gross when you have 12 columns...

.wrapper{
  display: grid;
  grid-template-areas:
    "nav nav cont cont cont cont cont cont cont cont cont cont";

  @media all and (max-width: 839px){
    grid-template-areas:
      "nav nav cont cont cont cont";
  }
}

回答1:


You can combine it with grid-template-columns like this:

.wrapper{
  display: grid;
  grid-template-areas:
    "nav cont";
  grid-template-columns:2fr 10fr;

  @media all and (max-width: 839px){
    grid-template-areas:
      "nav cont";
    grid-template-columns:1fr 4fr;
  }
}

Example:

.wrapper {
  display: grid;
  grid-template-areas: "nav cont";
  grid-template-columns: 2fr 10fr;
}

.nav {
  grid-area: nav;
  height: 100px;
  background: red;
}

.cont {
  grid-area: cont;
  height: 100px;
  background: blue;
}

@media all and (max-width: 839px) {
  .wrapper {
    grid-template-areas: "nav cont";
    grid-template-columns: 1fr 4fr;
  }
}
<div class="wrapper">
  <div class="nav">
  </div>
  <div class="cont">
  </div>
</div>



回答2:


Named areas are just shortcuts for named lines, and so you can use either. For example, your 12-column code can instead be written as:

.wrapper{
  display: grid;
  grid-template-columns: [nav-start] repeat(2, auto) [nav-end cont-start] repeat(10, auto) [cont-end];
}

The -start and -end line names define named areas in the same way that grid-template-areas does, and are sometimes more convenient to use.

(That said, I recommend usually doing what @temani-afif said, and instead just having two meaningful columns, using fr units to designate their relative sizes. Literal 12-column grids are an artifact of the old limitations that grid systems had to work in. But on the other hand, using actual multiple columns is sometimes clearer, especially if you're using gaps between the columns. Do whatever works best for you.)



来源:https://stackoverflow.com/questions/52359428/easier-way-use-css-grid-template-areas-to-span-multiple-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!