One day you'll be working on a project that needs a table. You have the option of making a table a few different ways: using HTML, using CSS, or using JavaScript. They each have their pros and cons, but if you don't want to deal with all of the <table> tags in HTML or write code for it in JavaScript, you can always use CSS.
It's relatively straight forward to make a simple table using CSS. All you need to know are the basics of HTML and CSS. To make a table without the <table> elements, you'll be using a lot of <div> elements. The good thing about <div> elements is that they don't come pre-loaded with styles like the <table> elements do. That means you can apply styles without wondering why something looks off.
We're going to walk through a quick guide on making a table with this method. The first thing you need is your HTML. We're going to make a 3 x 3 table to keep things simple.
<div class="table">
<div class="column">
<div class="row"></div>
<div class="row"></div>
<div class="row"></div>
</div>
<div class="column">
<div class="row"></div>
<div class="row"></div>
<div class="row"></div>
</div>
<div class="column">
<div class="row"></div>
<div class="row"></div>
<div class="row"></div>
</div>
</div>
You'll notice that there are some classes on these <div> tags. I like to keep things simple so we'll just use some basic names: table, row, and column. You can probably guess what each of the <div> elements are based on their class name alone.
At the moment if you opened this in a browser you wouldn't see anything. That's because there aren't any styles on these elements. Now it's time to write the CSS.
.table {
display: flex;
}
.column {
margin-bottom: 1em;
width: 100%;
}
.row {
border: 1px black solid;
height: 3em;
margin: auto;
width: 100%;
}
The styles for this table aren't complicated. The important thing to note is the flex value on the table class. This is what puts the column divs next to each other. In the row class, you'll see values for the border and height properties. These don't have to be here for your table to work. They're here right now so I can show you what this looks like.
Now you can write any code inside of the row divs and it'll show up in this table. This is by no means the only way to make a table using CSS. There's a whole thing on CSS Flexbox and CSS Grid that I'm writing and it'll definitely show you there's more to it.
Go use this code to make your own table and play around with it. Any time you play with code, you learn something new even if it's relatively small.
I hope this taught you something new! Or at least kept you occupied for a few minutes. :)
Hey! You should follow me on Twitter because reasons: https://twitter.com/FlippedCoding