I have an HTML table that's been created and populated dynamically with JavaScript.
I want to dynamically apply the CSS style and media queries to the HTML table.
Approaches I've tried.
- I defined the style in a separate file and reference it in the HTML file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="style.css" rel="stylesheet" />
<title>Document</title>
</head>
<body>
<table id="data-tb"></table>
<script>
// JavaScript code goes here...
</script>
</body>
</html>
The CSS style and that of media queries do not work. The styles didn't apply to the HTML table that was dynamically generated.
- I defined the style inside the HTML file within the
scripttag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="style.css" rel="stylesheet" />
<title>Document</title>
</head>
<body>
<table id="data-tb"></table>
<script>
document.head.innerHTML += `
<style>
body {
font-family: "Open Sans", sans-serif;
line-height: 1.25;
}
table {
border: 1px solid #ccc;
border-collapse: collapse;
margin: 0;
padding: 0;
width: 100%;
table-layout: fixed;
}
table caption {
font-size: 1.5em;
margin: 0.5em 0 0.75em;
}
table tr {
background-color: #f8f8f8;
border: 1px solid #ddd;
padding: 0.35em;
}
table th,
table td {
padding: 0.625em;
text-align: center;
}
table th {
font-size: 0.85em;
letter-spacing: 0.1em;
text-transform: uppercase;
}
@media screen and (max-width: 600px) {
table {
border: 0;
}
table caption {
font-size: 1.3em;
}
table thead {
border: none;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
table tr {
border-bottom: 3px solid #ddd;
display: block;
margin-bottom: 0.625em;
}
table td {
border-bottom: 1px solid #ddd;
display: block;
font-size: 0.8em;
text-align: right;
}
table td::before {
content: attr(data-label);
float: left;
font-weight: bold;
text-transform: uppercase;
}
table td:last-child {
border-bottom: 0;
}
}
</style>`;
// JavaScript code goes here...
</script>
</body>
</html>
In the second approach, the CSS style work. But the media queries for screen (max-width: 600px) do not work.
How can I dynamically apply the CSS style and media queries to the HTML table created and populated with JavaScript?