Styling Tables with CSS

CSSWeb DevelopmentFront End Technology

For styling the tables with CSS, we can set borders, collapse, set width and height. We can also set the padding, alig text in it, etc. Let us see some examples −

Example

To add borders to a table in CSS, use the borders property. Let us now see an example −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
   border: 2px dashed orange;
}
</style>
</head>
<body>
<h2>Team Ranking Table</h2>
<table>
<tr>
<th>Team</th>
<th>Rank</th>
<th>Points</th>
</tr>
<tr>
<td>India</td>
<td>1</td>
<td>200</td>
</tr>
<tr>
<td>England</td>
<td>2</td>
<td>180</td>
</tr>
<tr>
<td>Australia</td>
<td>3</td>
<td>150</td>
</tr>
<tr>
<td>NewZealand</td>
<td>4</td>
<td>130</td>
</tr>
<tr>
<td>SouthAfrica</td>
<td>5</td>
<td>100</td>
</tr>
<tr>
<td>WestIndies</td>
<td>6</td>
<td>80</td>
</tr>
<tr>
<td>Pakistan</td>
<td>7</td>
<td>70</td>
</tr>
</table>
</body>
</html>

Output

Example

To collapse table borders, use the border-collapse property in CSS. Let us see an example to collapse table borders −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
table {
   border-collapse: collapse;
   background-color: black;
   color: white;
}
th, td {
   border: 2px dashed yellow;
}
</style>
</head>
<body>
<h2>Team Ranking Table</h2>
<table>
<tr>
<th>Team</th>
<th>Rank</th>
<th>Points</th>
</tr>
<tr>
<td>India</td>
<td>1</td>
<td>200</td>
</tr>
<tr>
<td>England</td>
<td>2</td>
<td>180</td>
</tr>
<tr>
<td>Australia</td>
<td>3</td>
<td>150</td>
</tr>
<tr>
<td>NewZealand</td>
<td>4</td>
<td>130</td>
</tr>
<tr>
<td>SouthAfrica</td>
<td>5</td>
<td>100</td>
</tr>
<tr>
<td>WestIndies</td>
<td>6</td>
<td>80</td>
</tr>
<tr>
<td>Pakistan</td>
<td>7</td>
<td>70</td>
</tr>
</table>
</body>
</html>

Output

Example

To set the space between border and content, use the padding property as in the below example −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
table {
   border: 1px solid black;
   background-color: blue;
   color: white;
}
th, td {
   border: 1px solid black;
   padding: 20px;
   text-align: center;
}
table#demo {
   table-layout: fixed;
   width: 100%;
}
</style>
</head>
<body>
<h2>Team Ranking Table</h2>
<table id="demo">
<tr>
<th>Team</th>
<th>Rank</th>
<th>Points</th>
</tr>
<tr>
<td>India</td>
<td>1</td>
<td>200</td>
</tr>
<tr>
<td>England</td>
<td>2</td>
<td>180</td>
</tr>
<tr>
<td>Australia</td>
<td>3</td>
<td>150</td>
</tr>
<tr>
<td>NewZealand</td>
<td>4</td>
<td>130</td>
</tr>
<tr>
<td>SouthAfrica</td>
<td>5</td>
<td>100</td>
</tr>
</table>
</body>
</html>

Output

raja
Published on 30-Dec-2019 09:35:20
Advertisements