CSS 九宫格

CSS 九宫格

公共 CSS 属性

.square{
  position: relative;
  width: 100%;
  height: 0;
  padding-bottom: 100%; /* padding百分比是相对父元素宽度计算的 */
  margin-bottom: 30px;
}

.square-inner{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%; /* 铺满父元素容器,这时候宽高就始终相等了 */
}

.square-inner>li{
  width: calc(98% / 3);  /* calc里面的运算符两边要空格 */
  height: calc(98% / 3);
  margin-right: 1%;
  margin-bottom: 1%;
  overflow: hidden;
}

FlexBox

HTML:

<div class="square">
  <ul class="square-inner flex">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
  </ul>
</div>

CSS:

.flex {
  display: flex;
  flex-wrap: wrap;
}

.flex > li{
  flex-grow: 1; /* 子元素按1/n的比例进行拉伸 */
  background-color: #4d839c;
  text-align: center;
  color: #fff;
  font-size: 50px;
  line-height: 2;
}

.flex > li:nth-of-type(3n) { /* 选择个数是3的倍数的元素 */
  margin-right: 0;
}

.flex > li:nth-of-type(n+7) {  /* 选择倒数的三个元素,n可以取0 */
  margin-bottom: 0;
}

Grid

HTML

<div class="square">
  <div class="square-inner grid">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <div>7</div>
    <div>8</div>
    <div>9</div>
  </div>
</div>

CSS

.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 相当于 1fr 1fr 1fr */
  grid-template-rows: repeat(3, 1fr); /* fr单位可以将容器分为几等份 */
  grid-gap: 1%; /* grid-column-gap 和 grid-row-gap的简写 */
  grid-auto-flow: row;
}

.grid > div {
  color: #fff;
  font-size: 50px;
  line-height: 2;
  text-align: center;
  background: linear-gradient(to bottom, #f5f6f6 0%,#dbdce2 21%,#b8bac6 49%,#dddfe3 80%,#f5f6f6 100%);
}

Float

HTML

<div class="square">
  <ul class="square-inner float">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
  </ul>
</div>

CSS

.float::after {
  content: "";
  display: block;
  clear: both;
  visibility: hidden;
}

.float > li {
  float: left;
  background-color: #42a59f;
  text-align: center;
  color: #fff;
  font-size: 50px;
  line-height: 2;
}

.float > li:nth-of-type(3n) {
  margin-right: 0;
}

.float > li:nth-of-type(n+7) {
  margin-bottom: 0;
}

Table

HTML

<div class="square">
  <table class="square-inner table">
    <tbody>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
      </tr>
      <tr>
        <td>4</td>
        <td>5</td>
        <td>6</td>
      </tr>
      <tr>
        <td>7</td>
        <td>8</td>
        <td>9</td>
      </tr>
    </tbody>
  </table>
</div>

CSS

.table {
  border-collapse: separate;
  border-spacing: 0.57em;
  font-size: 14px;
  empty-cells: hide;
  table-layout: fixed;
}

.table > tbody > tr > td {
  text-align: center;
  background-color: #889esd8;
  overflow: hidden;
}

参考