2

I have a table (in a div with an id) and I want to apply styling on it (to collapse its borders) using CSS's universal selector combinator (*) and all of the div's descendants (in order to isolate the CSS styling just to this table in the div). Here's a snippet of the HTML code:

<div id="table1">
    <table>
        <tr>
            <th>1</th>
            <th>2</th>
            <th>3</th>
        </tr>
        <tr>
            <td>a</td>
            <td>b</td>
            <td>c</td>
        </tr>
    </table>
</div>

Here's a snippet of the CSS code:

div#table1 * {
    table {
        border-collapse: collapse;
    }
    td,
    th {
        border: 1px solid black;
        padding: 3px;
        text-align: center;
    }

    th {
        font-weight: bold;
        background-color: #E6E6E6;
    }
}

All but the table tag get styled (i.e. the table borders don't get collapsed).

If I apply just the table styling individually everything seems to work fine:

div#table1 table {
    border-collapse: collapse;

}
div#table1 * {
    td,
    th {
        border: 1px solid black;
        padding: 3px;
        text-align: center;
    }

    th {
        font-weight: bold;
        background-color: #E6E6E6;
    }
}

I don't understand why the styling doesn't work on the table tag when it's part of the CSS's Universal Selector Combinator. Is there a way to make it work without the individual styling for the table?

New contributor
atanas is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

1 Answer 1

3

The two CSS examples have slightly different targeting. In the working example:

div#table1 table {
    border-collapse: collapse;

}

This specifies that the table is a descendant of div#table1, which it is. However, in the non-working example:

div#table1 * {
    table {
        border-collapse: collapse;
    }
    ...
}

This specifies that the table is a descendant of something (anything) which is a descendant of div#table1, which it is not. There's no element in between the two in the hierarchy.

You can remove the nested table specifier in that case:

div#table1 * {
    border-collapse: collapse;
    td,
    th {
        border: 1px solid black;
        padding: 3px;
        text-align: center;
    }

    th {
        font-weight: bold;
        background-color: #E6E6E6;
    }
}

This would apply border-collapse: collapse; to any descendant of div#table1. (And the style rule only affects table elements in general anyway.)

Sign up to request clarification or add additional context in comments.

2 Comments

a good sulotuion could also be the use of & in nested selectors: div#table1 * { &table { ... } }
Unfortunately, I can't make the & work. I must be doing something wrong and might need to open a separate question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.