Exercise – creating table using css

Today I played around with css and the display: table / table-row / table-cell settings. And it worked out quite well. The reason for playing with this was to create a table without using the table-tag.

I am not religious regarding using or not using the table-tag to render the page, but some are out there, and so it is nice to know how to use css to create a table.

Below is the code that I used to get some data. What it does it looping the “root” of my personal development apache server. Then by using the div-tag and css a table is created.

This is the index.php file

<?php
# index.php

/*
* This file shall have a little menu in it. It shall also list up the folders we have
* in the root directory
*/
echo ‘<html>
<head>
<title>Localhost</title>
<link rel=”stylesheet” href=”style/localhost.css” type=”text/css” />

</head>

<body>’;

if ($handle = opendir(‘.’)) {
echo $_SERVER['SERVER_NAME'].” running on: “;
echo $_SERVER['SERVER_SOFTWARE'].”<br>”;
# echo “Directory handle: $handle\n”;
echo “<b>Files:</b>\n<br>”;

# This will be a test for css and tables
echo “<div class = \”table\”>\n”;
$rows = 1;
$cols = 0;
$files = 0;
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
if (strlen($file) > 2) {
# we shall change rows when we have created three columns
$cols++;

if ($cols == 5) {
echo “</div>\n”;
$cols = 1;
}

if ($cols == 1) {
echo “<div class = \”tr”.$rows.”\”>”;
$rows++;

if ($rows == 3) {
$rows = 1;
}
}

echo “<div class = \”td\”>”.$file.”</div>”;

}
}

closedir($handle);
echo “</div>”;
}

?>

And this is the CSS-file


/*
This style is used to check how to create tables in css
*/

div.table {
display: table;
table-layout: fixed;
background-color: rgb(120, 20, 90);
width:100%;

}

div.tr1 {
display: table-row-group;
background-color: #e5e5e5;
}

div.tr2 {
display: table-row-group;
background-color: #bfbfbf;
}
div.td {
display: table-cell;
vertical-align: top;
padding: 2px 0px 3px 0px;
border-bottom: 1px solid #d3d1d1;
width: 20px;
}

You can leave a response, or trackback from your own site.

Leave a Reply