html - 用 inline-block 创建完美的正方形

标签 html css

我想知道是否有一种方法可以使用 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>

现在它看起来还是有点像矩形。

最佳答案

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

/* 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;
}
<div class="container">
  <div class="legend">
    d
  </div>
  <div class="legend-text">
    Some legend
  </div>
</div>

关于html - 用 inline-block 创建完美的正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47464794/

相关文章:

html - CSS按钮添加顶栏

html - 基于百分比的导航

css - bootstrap.css 和 bootstrap-theme.css 有什么区别?

html - 在 bootstrap 3.3 和 jquery 1.1 中单击后,折叠按钮显示但不起作用

jquery - 为轮播横幅添加视差效果,使图像和文本以不同的速度移动

jquery - 悬停时更改类的属性

html - 如何让标签对齐

php - 处理表单处理的最佳实践

php - 使用 CSS 样式表格式化 PHP 值

jquery - 单击侧边栏中的元素时防止主窗口滚动