如何在CSS中制作2x2 Div的网格?

时间:2016-12-23 00:16:18

标签: html css

我正在尝试使用4个div在CSS中制作2x2网格,我可以做到。到目前为止,我的代码。我只是希望它是div上的4x4网格,填充容器。

    .Grades{
      width: 100%;
      height: 100%;
    
    
    }
    
    
    .desktopGrades{
      margin: 10px;
      box-sizing: border-box;
      float: left;
      width: 50%;
      height: 50%;
      clear: none;
    
    }
      <div class="grades">
    
    
        <div class="desktopGrades1">
          <h1>Maths</h1>
        </div>
        <div class="Desktopgrades2">
          <h1>Maths</h1>
        </div>
        <div class="desktopGrades3">
          <h1>Maths</h1>
        </div>
        <div class="desktopGrades4">
          <h1>Maths</h1>
        </div>
    
    
    
    
      </div>

1 个答案:

答案 0 :(得分:5)

您的代码中存在很多问题:

  1. HTML中没有类desktopGrades的元素。
  2. 您的元素没有desktopGrades类。
  3. CSS是CaSe SeNsItIvE。
  4. 您不能同时使用marginwidth来计算100%
  5. 要使用height,这很复杂。见解决方案#2。
  6. 工作代码段

    .grades {
      width: 100%;
      height: 100%;
      overflow: hidden;
    }
    .desktopGrades {
      box-sizing: border-box;
      padding: 10px;
      float: left;
      width: 50%;
      height: 50%;
    }
    .desktopGrades h1 {
      border: 1px solid #ccc;
    }
    <div class="grades">
      <div class="desktopGrades desktopGrades1">
        <h1>Maths</h1>
      </div>
      <div class="desktopGrades desktopGrades2">
        <h1>Maths</h1>
      </div>
      <div class="desktopGrades desktopGrades3">
        <h1>Maths</h1>
      </div>
      <div class="desktopGrades desktopGrades4">
        <h1>Maths</h1>
      </div>
    </div>

    替代解决方案

    * {
      box-sizing: border-box;
      margin: 0;
    }
    .grades {
      width: 100%;
      height: 100%;
      overflow: hidden;
      position: fixed;
      top: 0;
      left: 0;
    }
    .desktopGrades {
      padding: 10px;
      float: left;
      width: 50%;
      height: 50%;
    }
    .desktopGrades h1 {
      border: 1px solid #ccc;
      height: 100%;
    }
    <div class="grades">
      <div class="desktopGrades desktopGrades1">
        <h1>Maths</h1>
      </div>
      <div class="desktopGrades desktopGrades2">
        <h1>Maths</h1>
      </div>
      <div class="desktopGrades desktopGrades3">
        <h1>Maths</h1>
      </div>
      <div class="desktopGrades desktopGrades4">
        <h1>Maths</h1>
      </div>
    </div>