将div和内容放在主div中

时间:2018-10-28 09:47:38

标签: html css

我正在努力实现以下目标:

  1. 正方形内的文字(示例文字:“ 1/4”)应水平居中 和垂直。
  2. 四个正方形应该以相同的方式散布 主容器上的距离(红色)。
  3. 文字(示例文字:“名称”,“ Longer Name”等)应在正方形上方居中放置,并且不影响正方形的散布(第2点)

到目前为止,我得到的是下面的代码。如果有人能指出我正确的方向,我将不胜感激!

.container {
  background-color: red;
  width: 320px;
  height: 320px;
  margin: 30px auto 30px auto;
}

.inner {
  display: flex;
}

.inner-content {
    display: block;
   /* width: 25%;*/
    margin-left: auto;
    margin-right: auto;
    background-color: green;
  }

.text {
    width: 25%;
    text-align: center;
}

.square {
  margin-top: 5px;
  height: 25px;
  width: 25px;
  vertical-align: top;  
  text-align: center;
  color: #fff;
  font-size: 14px;
  font-weight: bold;
  text-align: center;
  background-color: black;
  box-shadow: 0 0 0 2px red, 0 0 0 5px black;
}
<div class="container">

  <div class="inner">
    <div class="inner-content">
      <span class="text">Name</span>
      <div class="square">
        1/4
      </div>
    </div>

    <div class="inner-content">
      <span class="text">Longer Name</span>
      <div class="square">
        1/4
      </div>
    </div>

    <div class="inner-content">
      <span class="text">Name</span>
      <div class="square">
        1/4
      </div>
    </div>

    <div class="inner-content">
      <span class="text">Yo</span>
      <div class="square">
        1/4
      </div>
    </div>

  </div>

1 个答案:

答案 0 :(得分:1)

看看下面的例子:

* {
  box-sizing: border-box;
}

.container {
  background-color: red;
  width: 320px;
  height: 320px;
  margin: 30px auto 30px auto;
  padding: 5px;
}

.inner {
  display: grid;
  grid-template-columns: repeat(4, 1fr); /* fix spreading */
  grid-column-gap: 5px;
}

.inner-content {
  background-color: green;
  text-align: center;
}

.text {
  width: 100%;
}

.square {
  margin: 5px auto; /* fix box centering */
  height: 25px;
  width: 25px;
  vertical-align: top;  
  text-align: center;
  color: #fff;
  font-size: 14px;
  font-weight: bold;
  background-color: black;
  box-shadow: 0 0 0 2px red, 0 0 0 5px black;
  line-height: 25px; /* fix vertical center */
}
<div class="container">

  <div class="inner">
    <div class="inner-content">
      <span class="text">Name</span>
      <div class="square">
        1/4
      </div>
    </div>

    <div class="inner-content">
      <span class="text">Longer Name</span>
      <div class="square">
        1/4
      </div>
    </div>

    <div class="inner-content">
      <span class="text">Name</span>
      <div class="square">
        1/4
      </div>
    </div>

    <div class="inner-content">
      <span class="text">Yo</span>
      <div class="square">
        1/4
      </div>
    </div>

  </div>