使用内联块创建完美的正方形

时间:2017-11-24 00:16:07

标签: html css css3

我想知道是否有办法使用display: inline-block创建一个完美的正方形。原因是我想把它放在文本旁边,例如



.legend {
  display: inline-block;
  color: rgba(0, 0, 0, 0);
  width: 1em;
  background-color: lightblue;
}

<div>
  <div class="legend">
    d
  </div>
  <div style="display: inline-block">
    Some legend
  </div>
</div>
&#13;
&#13;
&#13;

现在它仍然看起来有点矩形。

2 个答案:

答案 0 :(得分:1)

您也可以简单地指定div的高度。请考虑以下事项:

&#13;
&#13;
/* The container needs to be relatively positioned */
.container {
  position: relative;
}

/* The legend is absolutely positioned, but in relation to its 
 * container.
 * We also apply a common trick to place it at the vertical center of
 * its parent: position the top bound at 50% of the parent's height.
 * then transform the position to move it up by 50% of its own height. 
 */
.legend {
  display: inline-block;
  color: rgba(0, 0, 0, 0);
  width: 1em;
  height: 1em;
  background-color: lightblue;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

/* This div is decisive for the whole thing's height.
 * Since the legend is positioned in an absolute way, we need to make 
 * room for it by moving this div to the right (margin-left)
 */
.legend-text {
  margin-left: 1em;
  padding: 5px;
  display: inline-block;
}
&#13;
<div class="container">
  <div class="legend">
    d
  </div>
  <div class="legend-text">
    Some legend
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

非常简单。将高度添加到.legend

.legend {
  display: inline-block;
  color: rgba(0, 0, 0, 0);
  width: 1em;
  height: 1em;// just add this line
  background-color: lightblue;
}