简体   繁体   中英

CSS only works for table and not working for table header (th)

I am appending html dynamically using Javascript and want to append some css along with the html. In my code, only the css for table is being picked up by the browser, the css for th is not showing up.

Javascript

var html = "<table class = 'table'>";
    html += "<thead>";
        html += "<tr><th>";
        html += "Name: " + data.name;
        html += "</th></tr>";
    html += "</thead>";

    html += "<tbody>";
        html += "<tr><td>";
        html += "Address: " + data.address;
        html += "</td></tr>";
        html += "<tr><td>";
        html += "Phone: " + data.phone;
        html += "</td></tr>";
    html += "</tbody>";
html += "</table>";

$(".info").html(html);

CSS

.table {
    border: 1px solid red;
}

.th {
    /* not applied successfully */
    color: red; 
}

Why is this happening?

You did not specify the class th . You must do <th class='th'> according to your CSS.

Or you can change your stylesheet: Just remove the dot in front of th .

You have the .table class but there isn't a class for .th

    html += "<tr><th class='th'>";
    html += "Name: " + data.name;
    html += "</th></tr>";

Maybe try and change the CSS to

.table {
border: 1px solid red;

}

th {
/* not applied successfully */
color: red; 
}

getting rid of the class identifier

The reason this is happening is you don't have a matching CSS selector for the <th element. The selectory you expect to work is looking for elements that have a class of .th , yet, there isn't any.

One solution would be to remove the class selector in your CSS and just use the element itself:

th {
  color: red
}

(Notice there is not dot)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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