CSS Table

Using CSS to Style Tables

Up to this point, as we haven’t applied any CSS styling to our tables, our example tables have not been too pleasing to the eye.  CSS offers us several properties to customize how our tables appear on the page:
propertiesWe’re already familiar with the color and text-align properties, but let’s see examples of the other styles in action.

Setting Table Width

We can set the overall width of a table by applying a class to the <table> element:
table-widthThe width of the columns is automatically established by the browser to accommodate the cell contents, but we don’t have to accept this format.

Setting Column Width in Pixels

We can set the width of columns by setting the widths of the first row of data cells:
table-col-widthNotice that due to the enforced width, some cell contents had to wrap to an additional line.

Setting Column Width in Percent

Rather than pixels, we can also set column widths to be a percent of the total available width:


CSS provides us plenty of flexibility when generating borders around elements.  There are multiple properties that affect the border that displays on the page:

The border-collapse Property


Customizing Borders

By using the other three properties, we can create custom borders for our table:

Using CSS Border Shorthand

When specifying multiple border properties, we can use the CSS border shorthand to reduce the statement to a single line:

Adding Cell Padding

By setting the padding property, we can make sure there is at least that much white space around our cell contents.  This keeps the actual cell contents from displaying too closely to the borders:
adding-paddingDifferent border and padding settings can be set for the top, bottom, left, and right sides of elements.

Setting a Background Color

By setting the background-color property, we can change our table’s background away from the default:

Using Background Color on Rows

color-rowThis is a handy way to make our table rows show in alternating background colors.  This technique makes reading wide tables far easier for viewers.