简体   繁体   English

通过规则的 css 属性(填充)不起作用,而相同的 css 内联应用则有效

[英]css properties (padding) via a rule doesn't work, whereas same css inline-applied does

I have the following code and cannot figure out why it doesn't work:我有以下代码,无法弄清楚为什么它不起作用:

 table { border: 1px solid black; } table.whole > tr > td { padding: 20px 0 20px 0; }
 <:-- doesn't work via css rule --> <table class="whole"> <tr> <td> <table> <tr> <td>abcd</td> </tr> </table> </td> </tr> </table> <hr> <!-- works inline --> <table> <tr> <td style="padding:20px 0 20px 0"> <table> <tr> <td>abcd</td> </tr> </table> </td> </tr> </table>

May I misunderstand how the child selector > works or is there some kind of limitation here, or a bug?...我可能会误解子选择器>的工作原理还是这里有某种限制或错误?...

If you inspect your code in the Chrome devtools, you will see that the browser has automatically inserted the required<tbody> element between the <table /> and rows for you.如果您在 Chrome 开发工具中检查您的代码,您将看到浏览器已自动为您在<table />和行之间插入所需的<tbody>元素。 Because of this, the <tr /> is no longer the direct descendent of the <table /> .因此, <tr />不再是<table />的直接后代。 So the issue is that your HTML is malformed/not adhering to the spec.所以问题是您的 HTML 格式错误/不符合规范。 If you add the <tbody /> element and rewrite your CSS accordingly, it will work just fine:如果您添加<tbody />元素并相应地重写您的 CSS,它将正常工作:

 table { border: 1px solid black; } table.whole > tbody > tr > td { padding: 20px 0 20px 0; }
 <!-- doesn't work via css rule --> <table class="whole"> <tbody> <tr> <td> <table> <tr> <td>abcd</td> </tr> </table> </td> </tr> </tbody> </table>

In HTML, there must be a <tbody> element between <table> and <tr> elements.在 HTML 中, <table><tr>元素之间必须有一个<tbody>元素。 Chrome is being nice, so it helpfully inserts it for you. Chrome 很好,所以它会为您插入它。 However, that breaks your CSS, because now <tbody> is the child of <table> , and not <tr> .但是,这会破坏您的 CSS,因为现在<tbody><table>的孩子,而不是<tr>

Solution:解决方案:

Include a <tbody> (otherwise it would be invalid and confusing), and change your CSS code to:包括一个<tbody> (否则它将是无效和混乱的),并将您的 CSS 代码更改为:

table.whole > tbody > tr > td {
    padding: 20px 0 20px 0;
}

 table { border: 1px solid black; } table.whole > tbody /*...and put it here. */ > tr > td { padding: 20px 0 20px 0; }
 <table class="whole"> <tbody> <.-- include a <tbody> element... --> <tr> <td> <table> <tbody> <tr> <td>abcd</td> </tr> </tbody> </table> </td> </tr> </tbody> </table>

Note: the inline styles work because they don't have any random selector errors because they're placed right in the <tbody> element.注意:内联 styles 可以正常工作,因为它们没有任何随机选择器错误,因为它们位于<tbody>元素中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM