css - 当文本设置为空白时,如何保留文本贡献的高度

标签 css

考虑一个内联 block CSS 元素,它可以包含文本,并且有一些漂亮的填充。

根据内联 block 中是否有任何文本,元素的高度会有所不同:

.text-holder {
  display: inline-block;
  color: #ffffff;
  padding: 10px;
  vertical-align: top;
}
.text-holder.black { background-color: #000000; }
.text-holder.grey { background-color: #606060; }
<div class='text-holder black'>I HAVE TEXT</div>
<div class='text-holder grey'></div>

如何确保这些元素的高度相同,无论元素内部是否有任何文本,无论字体大小如何?

起初我考虑过 min-height,但我不认为这适用于可变字体大小。

最佳答案

空时使用零空格字符:

.text-holder {
  display: inline-block;
  color: #ffffff;
  padding: 10px;
  vertical-align: top;
}
.text-holder.black { background-color: #000000; }
.text-holder.grey { background-color: #606060; }

.text-holder:empty::before {
  content:"\200B";
}
<div class='text-holder black'>I HAVE TEXT</div>
<div class='text-holder grey'></div>

您也可以为所有元素保留它,因为它的宽度为 0:

.text-holder {
  display: inline-block;
  color: #ffffff;
  padding: 10px;
  vertical-align: top;
}
.text-holder.black { background-color: #000000; }
.text-holder.grey { background-color: #606060; }

.text-holder::before {
  content:"\200B";
}
<div class='text-holder black'>I HAVE TEXT</div>
<div class='text-holder grey'></div>

只要注意是否有前导空格:

.text-holder {
  display: inline-block;
  color: #ffffff;
  padding: 10px;
  vertical-align: top;
}
.text-holder.black { background-color: #000000; }
.text-holder.grey { background-color: #606060; }

.text-holder::before {
  content:"\200B";
}
<div class='text-holder black'>I HAVE TEXT</div><br>
<div class='text-holder black'> I HAVE TEXT</div>
<div class='text-holder grey'></div>

关于css - 当文本设置为空白时,如何保留文本贡献的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57896415/

相关文章:

html - div 中的 CSS 对齐仍然存在问题

javascript - 选择国家时改变颜色

html - 打开 paper-dropdown-menu 时滚动网页

jquery - 鼠标悬停/鼠标离开 : 3rd image positioning and toggling on and off

css - 长 URL 不会留在 Bootstrap 列中

html - 为什么第 nth-of-type/nth-child 不适用于嵌套元素?

javascript - HTML/CSS : Create a new element?

javascript - 如何将文本悬停在 div img 上?

带有链接的 jQuery ul - 只影响 li child

html - 为什么这种 HTML 和 CSS 组合设置字体颜色和样式失败?