一个可选中的自适应布局效果

2019/04/20 html

记录下张鑫旭大佬的每周小测,这次的题目是实现一个自适应的布局效果,且要有选中态

github-css-quiz5.jpg

DEMO

<ul class="color-container">
  <li>
    <input id="color1" type="radio" name="color" />
    <label for="color1" class="color-item"></label>
  </li>
  ...
</ul>
ul {
  --width: calc((100vw - 20px) / 5 - 10px);
  display: grid;
  padding: 10px;
  grid-template-columns: repeat(5, 1fr);
  grid-auto-rows: var(--width);
  grid-gap: 10px;
  background: #fff;
  border: 1px #e5e5e5 solid;
  list-style-type: none;
}
/*可选中的input radio*/
input {
  display: none;
}
/*色块*/
.color-item {
  display: flex;
  width: 100%;
  height: 100%;
  overflow: hidden;
  word-break: break-all;
}
/*色块选中效果*/
input:checked + .color-item {
  box-shadow: 0 0 0 4px black;
}

/*色块背景*/

li:nth-child(7n + 1) .color-item {
  background: #424242;
}
li:nth-child(7n + 2) .color-item {
  background: #8c8c8c;
}
...

实现

  1. 布局使用 grid 布局, grid-template-columns: repeat(5, 1fr) 可以使列五等分,行高可以使用固定值,也可以让子元素的 padding-top 为 100% 来完成正方形。
  2. 使用 radio 来完成选中态,radio 的语义化更加强烈一些,相比于使用 a 标签加上 tabIndex 好很多

code pen DEMO

Search

    Table of Contents