首页 > 解决方案 > 如何在 CSS 中定义和使用类?

问题描述

我以前几乎从未用过 CSS 编码,我在我的 web 开发课程的 power point 中看到了这一点(它最初是用法语写的,所以我不确定我的翻译是否完全准确):

The <p> with the property class=indented and inside the element <td> will have the following CSS properties:
td p .indented {text-indent: 50px;}

所以我尝试使用此代码对其进行测试,但它不起作用:

    <body>
        this is the body of the document <br>
        <style>
            td p .indented {font-weight: bold; color:red}
            td {color:blueviolet}
        </style>
        <table>
            <tr>
                <th> 1 </th>
                <th> 2 </th>
                <th> 3 </th>
            </tr>
            <tr>
                <td><p>test</p></td>
                <td>test</td>
                <td><p class=indented>test</p></td>
            </tr>
        </table>
    </body>

所有 3 个test都以紫色显示,但没有以红色和粗体文本显示。难道我做错了什么?谢谢

标签: htmlcss

解决方案


你的 CSS 规则有一个小错误。td p .indented目标元素的类indentedp元素的后代,而元素的后代又是td元素的后代。

您可能正在寻找的是使用作为元素子p级的类来定位元素。删除选择器定义之间和中的空格:indentedtdp.indented

    <body>
        this is the body of the document <br>
        <style>
            td p.indented {font-weight: bold; color:red}
            td {color:blueviolet}
        </style>
        <table>
            <tr>
                <th> 1 </th>
                <th> 2 </th>
                <th> 3 </th>
            </tr>
            <tr>
                <td><p>test</p></td>
                <td>test</td>
                <td><p class=indented>test</p></td>
            </tr>
        </table>
    </body>


推荐阅读