Html 内容感知 CSS - 仅在内容可用时应用样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9063446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Content aware CSS - apply style only if content is available
提问by mspir
Is it possible to have a css style be aware of whether the element it is being applied to has some sort of content or not? I am currently using tables (forced to since the end user uses cms to create pages) with a css for each cell, as so
是否可以让 css 样式知道它所应用的元素是否具有某种内容?我目前正在使用表格(因为最终用户使用 cms 创建页面而被迫使用),每个单元格都有一个 css,如此
<table>
<tr>
<td class="someClass">Test value 1</td>
<td class="someClass">Test value 2</td>
</tr>
<tr>
<td class="someClass">Test value 3</td>
<td class="someClass"></td>
</tr>
</table>
As displayed, there is the chance that a table cell is left empty. Is there a way to make "someClass" aware of this and not apply the style to this cell?
如图所示,表格单元格有可能留空。有没有办法让“someClass”意识到这一点,而不是将样式应用到这个单元格?
I am sure there is some js hack I could apply, but I wonder if it is possible with pure css. Long shot?
我确信我可以应用一些 js hack,但我想知道纯 css 是否可行。远射?
Thanks.
谢谢。
回答by BoltClock
Simply use the :empty
pseudo-class like so:
只需:empty
像这样使用伪类:
td.someClass:not(:empty) {
/* Styles */
}
As Petr Marek mentions it's not very reliable as a cross-browser solution, so if you mustsupport older browsers (IE8 and older) you willneed JS (which you can probably figure out yourself). Otherwise, the above CSS rule will work just fine.
正如 Petr Marek 所提到的,它作为跨浏览器解决方案并不是很可靠,因此如果您必须支持旧浏览器(IE8 及更早版本),您将需要 JS(您可能会自己弄清楚)。否则,上面的 CSS 规则将正常工作。
You can find the browser compatibility of :not()
and :empty
here
你可以找到的浏览器的兼容性:not()
和:empty
这里
回答by Shane
The only thing I can think of that relates to your question is psuedo-classes, such as empty. Here is an example:
我能想到的唯一与您的问题有关的是伪类,例如空的。下面是一个例子:
<html>
<head>
<title>Example</title>
<style type="text/css">
.cell:not(:empty) {
background-color: red;
}
.cell:empty {
background-color: blue;
}
</style>
</head>
<body>
<table><tBody>
<tr><td class="cell"></td><td class="cell">Not empty</td></tr>
<tr><td class="cell">Not empty</td><td class="cell"></td></tr>
</tBody></table>
</body>
</html>
In modern browsers, you will see that empty cells are blue and cells with content are red. The key here is the first line of CSS, .cell:not(:empty). This applies the CSS if the element does not have the psuedo-class :empty applied.
在现代浏览器中,您会看到空单元格为蓝色,而包含内容的单元格为红色。这里的关键是 CSS 的第一行,.cell:not(:empty)。如果元素没有应用伪类 :empty,这将应用 CSS。
回答by mreq
No, with pure cross-browsercss it is not. You will have to edit their cms or use javascript.
不,纯跨浏览器css 不是。您将不得不编辑他们的 cms 或使用 javascript。