逗号分隔的跨度与纯CSS

Zol*_*ási 12 html css css3

我有 - 比方说 - 我的页面上有4个跨度.每个内容都由我的viewmodel中的knockout填充.有时几个内容的内容是空的.我想以一种漂亮的,逗号分隔的方式显示它们,考虑可能的空白.

我尝试了以下HTML和CSS.

版本1

它还显示空跨区的逗号

.comma:not(:last-child):after {
  content: ", ";
}
Run Code Online (Sandbox Code Playgroud)
<span class="comma">A</span>
<span class="comma">B</span>
<span class="comma"></span>
<span class="comma">D</span>
Run Code Online (Sandbox Code Playgroud)

版本2

如果最后一个跨度为空,它会显示(可视)最后一个逗号.

.comma:not(:empty):not(:last-child):after {
  content: ", ";
}
Run Code Online (Sandbox Code Playgroud)
<span class="comma">A</span>
<span class="comma">B</span>
<span class="comma">C</span>
<span class="comma"></span>
Run Code Online (Sandbox Code Playgroud)

无论差距在哪里(如果有的话),我怎么能调整它才能始终正确渲染?我只需要支持现代浏览器(IE9 +等).

fca*_*ran 13

我颠倒了逻辑,将逗号作为before伪元素的内容

示例:http://codepen.io/anon/pen/NPdbbw

/* remove extra space before the comma */
.comma:not(:first-child) {
  margin-left: -.3em;  
}

/* no need to display empty elements */
.comma:empty {
  display: none;
}

.comma:not(:first-child):before {
  content: ", ";
}
Run Code Online (Sandbox Code Playgroud)

如果第一个.comma元素也可以为空,那么这是一个更复杂的方法

http://codepen.io/anon/pen/BypQRd

.comma:not(:first-child) {
  margin-left: -.3em;  
}

/* next 2 rules are for spacing when the first .comma is empty too */
.comma:first-child:empty ~ .comma:not(:empty) {
  margin-left: 0;  
}

.comma:first-child:empty ~ .comma:not(:empty) ~ .comma:not(:empty) {
  margin-left: -.3em;  
}

.comma:empty {
  display: none;
}

.comma:not(:first-child):before {
  content: ", ";
}

.comma:not(:first-child):before {
  content: ", ";
}

.comma:empty + .comma:not(:empty):before {
  content : "";
}

.comma:not(:empty) ~ .comma:empty + .comma:not(:empty):before {
  content : ", ";
}
Run Code Online (Sandbox Code Playgroud)

最后一个示例已经成功地针对4个元素的所有可能组合进行了测试


:empty有关MDN上可用的伪类的更多信息


Cho*_*ett 5

转一圈。而不是把一个逗号的跨度后,就把它之前它之前(任何距离回来了!)由非空跨度每个跨度:

.comma:not(:empty) ~ .comma:not(:empty):before {
  content: ", ";
}
Run Code Online (Sandbox Code Playgroud)

小提琴