HTML / CSS如何使用grid-template属性

时间:2018-11-19 13:03:16

标签: html css css3 css-grid

做一些HTML / CSS编码作业,我想为我的按钮创建一个网格模板,以便将它们定位在相对位置,例如在游戏中,向上按钮在顶部,右按钮在右侧等。任何帮助表示赞赏。预先感谢。

#controller>.dpad {
  display: grid;
  grid-template-areas: " main right header footer ";
}

#controller>.dpad>button[env3d-key^="KEY_UP"] {
  grid-area: header;
}

#controller>.dpad>button[env3d-key^="KEY_LEFT"] {
  grid-area: main;
}

#controller>.dpad>button[env3d-key^="KEY_RIGHT"] {
  grid-area: right;
}

#controller>.dpad>button[env3d-key^="KEY_DOWN"] {
  grid-area: footer;
}
<div id="controller">
  <div class="dpad">
    <button env3d-key="KEY_UP">UP</button>
    <button env3d-key="KEY_LEFT">LEFT</button>
    <button env3d-key="KEY_RIGHT">RIGHT</button>
    <button env3d-key="KEY_DOWN">DOWN</button>
  </div>
  <button env3d-key="KEY_A">A</button>
  <button env3d-key="KEY_Z">Z</button>
</div>

2 个答案:

答案 0 :(得分:1)

#controller>.dpad {
  display: grid;
  grid-template-areas: ". header ."
                      "main . right"
                      ". footer .";
}

#controller>.dpad>button[env3d-key^="KEY_UP"] {
  grid-area: header;
}

#controller>.dpad>button[env3d-key^="KEY_LEFT"] {
  grid-area: main;
}

#controller>.dpad>button[env3d-key^="KEY_RIGHT"] {
  grid-area: right;
}

#controller>.dpad>button[env3d-key^="KEY_DOWN"] {
  grid-area: footer;
}
<div id="controller">
  <div class="dpad">
    <button env3d-key="KEY_UP">UP</button>
    <button env3d-key="KEY_LEFT">LEFT</button>
    <button env3d-key="KEY_RIGHT">RIGHT</button>
    <button env3d-key="KEY_DOWN">DOWN</button>
  </div>
  <button env3d-key="KEY_A">A</button>
  <button env3d-key="KEY_Z">Z</button>
</div>

在空白区域使用.

答案 1 :(得分:1)

友善的docs here。官方spec here

#controller .dpad {
  display: grid;
  grid-template-areas: "key-a key-a . . . top ." " . key-z key-z . left bottom right";
  grid-gap: 6px;
}

#controller button {
  padding: 21% 0;
  font-size: 3.2vw;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  text-shadow: 1px 1px 3px rgba(0, 0, 0, .42);
  border-radius: 6px;
  font-weight: 700;
}

#controller button[env3d-key^="KEY_UP"] {
  grid-area: top;
}

#controller button[env3d-key^="KEY_LEFT"] {
  grid-area: left;
}

#controller button[env3d-key^="KEY_RIGHT"] {
  grid-area: right;
}

#controller button[env3d-key^="KEY_DOWN"] {
  grid-area: bottom;
}

#controller button[env3d-key^="KEY_A"] {
  grid-area: key-a;
}

#controller button[env3d-key^="KEY_Z"] {
  grid-area: key-z;
}
<div id="controller">
  <div class="dpad">
    <button env3d-key="KEY_UP">UP</button>
    <button env3d-key="KEY_LEFT">LEFT</button>
    <button env3d-key="KEY_RIGHT">RIGHT</button>
    <button env3d-key="KEY_DOWN">DOWN</button>
    <button env3d-key="KEY_A">A</button>
    <button env3d-key="KEY_Z">Z</button>
  </div>

</div>