CSS Display-table

Contact Us or call 1-877-932-8228
CSS Display-table

CSS Display-table

The CSS display property allows us to apply table properties to arbitrary elements - to make, for example, a div behave like a table, a table row, or a table cell. This is particularly useful when trying to center content horizontally, as we can leverage the vertical-align property. Let's look at an example:

Code Sample:

<meta charset="UTF-8">
<title>CSS Table Display</title>
<h1>CSS Display Table</h1>
<div style="display: table; width: 300px; margin: 10px auto; background: #f00;">
	<div style="display: table-cell; vertical-align: middle; text-align: center; color: #fff; padding: 20px;">
		<p>This element is centered vertically and horizontally</p>

Our page is fairly simple: two div elements, one contained within the other, and some text inside the inner div. We style the outer element with a red background and the inner with white text.

We set the display property of the outer div to table and the display property of the inner div to table-cell. The inner element now behaves like a table cell, giving us the ability to center its text both horizontally (text-align: center) and vertically (vertical-align: middle):

CSS table display

A great thing about this technique is that we can selectively give the elements "table-like behavior": we might display those divs to behave as tables when viewed on a desktop, but use a media query to display them differently when viewed from a smaller screen like on a smartphone.