html – 当span元素为空时,如何不显示css填充

我一直在努力解决以下问题.

如果您运行此代码,您会注意到蓝色和红色元素.
当没有要显示的文本(span为空)时,如何隐藏“红色元素”.我想用’蓝色元素’做同样的事情,当里面没有文字时,它应该是不可见的.
显示的原因是填充,但我想填充,因为它看起来不错.
我相信你们是最好的,并找到解决方案.
问候!

.myClassDer {
  font-size: 34px;
  color:white;
  background: blue;
  color: white;
  border-radius: 25px;
  padding: 7px;
  width: auto;
  height: auto; 
}

.myClassDie {
  font-size: 34px;
  color:black;
  background: red;
  color: white;
  border-radius: 25px;
  padding: 7px;
  width: auto;
  height: auto; 
}
最佳答案
如果您不需要support for IE8,则可以使用伪状态:空(here for more examples)来重置无内容的.myClassDie实例的填充,使用以下代码.

.myClassDie:empty
{
   padding:0;
}

更新您的工作示例,它变为:

.myClassDer
{
  font-size: 34px;
  color:white;
  background: blue;
  color: white;
  border-radius: 25px;
  padding: 7px;
  width: auto;
  height: auto; 
}

.myClassDie
{
  font-size: 34px;
  color:black;
  background: red;
  color: white;
  border-radius: 25px;
  padding: 7px;
  width: auto;
  height: auto; 
}

.myClassDie:empty
{
   padding:0;
}

我在其中插入了两个< span class =“myClassDie”>向您展示有和没有内容的行为.

由于“空”案例的有效隐形,如果您想要一个更紧凑的解决方案,您可以将两个单独的规则折叠成一个,只需设置:

.myClassDie:not(:empty)
{
   font-size: 34px;
   color:black;
   background: red;
   color: white;
   border-radius: 25px;
   padding: 7px;
   width: auto;
   height: auto; 
}

在这种情况下,仅当.myClassDie不为空时,您才会应用所有属性.

这对于这种特定情况是等效的,但是如果你想看到这个DIV也是空的,只限于重置填充(例如因为它有固定的大小或边框),你必须使用第一个解决方案,而不是更紧凑的解决方案.

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些