Hướng dẫn table html css codepen
The Here’s a very simple demo of tabular data: It is data that is useful across multiple axes. Imagine running
your finger across a row (horizontal) to see a single person and relevant information about them. Or up and down a column (vertical) to get a sense of the variety or pattern of data on that point. One thing we didn’t do in the very basic example above is semantically indicate that the first row was the header of the table. We probably should have. That entire first row contains no data, it is simply the titles of columns. We can do that with the
That HTML would be like this: When you use Along with Back before HTML5, the It can be used, for example, to
repeat the header in the case of a visually very tall/long table where it may be easier to see the column titles at the bottom than the top. Although you don’t necessarily need to use it that way. The individual cells of a table are always one of two elements: Using our existing simple demo, the top row is all headers. Not data, just titles for the data. All the rest of the rows are data. So: Most
tables you will ever see use colors and lines to distinguish different parts of the table. Borders are very common. By default, all table cells are spacing out from one another by 2px (via the user-agent stylesheet), like this: Notice the slight extra gap between the first row and the rest. That is caused by the default border-spacing being applied to the But far more common is to remove that space. That property is completely ignored and the space collapsed if you do: Just a little padding, borders, and making those There are two important attributes that can go on any table cell element ( You’ll have to do a bit of mental math when you start working with connected cells. Colspan is fairly easy. Any table cell is “worth” one, unless it has a Rowspan is similar, it’s just a little harder and more of a mental leap, because columns aren’t grouped like rows are. If a table element has a It can be awkward to work out in your head, but we’re
developers here, we can do it =). Often these attributes are used in really simple ways like connecting a few related table headers: The table element itself is unusual in how wide it is. It behaves like a block-level element (e.g. If the amount of text in the tables widest row only happens to be 100px wide, the table will be 100px wide. If the amount of text (if put on one line) would be wider than the container, it will wrap. However if text is told to not wrap (i.e. Sometimes it makes sense for tabular data to have two axes. Like a cross-reference situation. A multiplication table is an example of this: I might skip a It’s a good time to take a break and discuss the when of tables. Perhaps you’ve heard the generic advice: tables are for tabular data (see the first sentence of this blog post). The “would this make sense in a spreadsheet?” test is usually appropriate. What kinds of things are appropriate in tables? Here are some: a plan/pricing/features comparison, bowling scores, an internal grid of employee data, financial data, a calendar, the nutrition facts information
panel, a logic puzzle solver, etc. You might occasionally hear: tables are unsemantic. That’s not true – they semantically indicate tabular data. Tables are the right choice when that is the case. An inappropriate use for tables is for layout. That may seem counter-intuitive. At a glance at how tables work may make them seem ideal for layout. Easy to control, extremely logical, predictable, and not-at-all fragile. There
are some significant problems with using tables for layout though. First, HTML tags mean things. As we covered, table elements semantically describe tabular data. Using them for anything else is a breach of semantic duty. You aren’t going to get a fine in the mail, but you aren’t getting as much value from your HTML as you could. Talking about semantics is a little difficult sometimes (some reads:
1, 2, 3, 4,
5), so let’s talk about something we all generally agree on (even if we aren’t as good as it as we want to be): websites should be accessible. One part of accessibility is screen readers. Screen readers read tables from top to bottom, left to right. That means the order of how your site is presented is dictated by the table structure, which is dictated by visual choices not accessibility choices.
Not to mention a screen reader may even announce the start of tabular data which would be worse than useless. Speaking of source order, that affects more than accessibility. Imagine a “sidebar on the left” layout. A table would dictate that table comes first in the source order, which while also being bad for accessibility, is likely bad for SEO as well, potentially valuing your ancillary content above primary content. Could you fix the SEO issues by using semantic tags within the
table tags? Possibly somewhat, but now you’re using double the HTML. If you really need the layout abilities of a table but want to use semantic tags, see the next section. If you are somehow absolutely stuck using table tags for layout, use the ARIA As I write this in the latter half of 2013, tables have become far less prevalent and even appealing as a layout choice. We’re seeing a lot more use of fixed and absolute positioning which you
cannot do inside a table. We’re seeing flexbox being awesome and being right on the edge of mainstream usability. We’re seeing grid layout starting to grow up. We’re seeing inline-block be used powerfully. We’re seeing the fragility of floats in the olden days fade away. Rarely do you see modern websites touch tables for layout. The last holdout is HTML emails. The landscape of what renders emails is super wide. It is everything we deal with on the web, plus the world of native apps on
both mobile and desktop on operating systems new and ancient. You can do some progressive enhancement for emails, but the layout itself is still generally regarded as being safest done in tables. That is substantiated by the fact that the major email sending services still all offer templates as tables. CSS has properties to make any element you wish behave as if it was a table element.
You’ll need to structure them essentially as you would a table, and it will be subject to the same source-order-dependency as a table, but you can do it. I’m not crapping on it either, it’s genuinely useful sometimes. If that layout style solves a problem and has no negative order implications, use it. Don’t use inline styles, but just for understanding here’s how that would go: A handy trick here is that you don’t even need the table-row element in there if you don’t want. A
bunch of You always alter the display property of the element to get the table-style behavior. Here’s the values: Notice there is no There is also If you want to learn a lot more about using semantic elements but also table-style layout, check out the book Everything You Know About CSS Is Wrong!
I’ve never been a huge fan of that title as it suggests that using this table style layout is the right way and any other layout technique you use is the wrong way. But as I’ve said, this can be tremendously useful and I’m glad it’s in
CSS. Just be acutely aware that no matter what kind of elements you use to create a table-based layout, it still subject to the same problems (largely source order dependency). There is a few elements above we haven’t touched on yet. Let’s look at all the HTML table related elements. You know what, we might as well use a table to do it: There are suprisingly few attributes that are specific to tables. Of course you can use class and ID and all the typical global attributes. There used to be quite a few, but most of them were specific to styling and thus deprecated (as that is CSS’s job). Don’t use any of these. The are deprecated. While they may work in some browsers today, there is a chance they stop working in the future. There is an implied vertical stacking of table elements, just like there is in any HTML parent > descendent scenario. It is important to understand in tables because it can be particularly tempting to apply things like backgrounds to the table itself or table rows, only to have the background on a table cell “override” it (it is actually just sitting on top). Here’s how that looks (using Firefox 3D
feature in its dev tools): You can use most CSS properties on table elements. These properties are either unique to table elements or they behave uniquely on table elements. This list isn’t exhaustive. There are other CSS quirks that are relevant to tables. For instance, you can’t relatively position a table cell in which to either nudge it around or absolutely position things within it. There are ways though. If you can think of more CSS weirdness with tables, share in the comments below. WebKit does this: I inspected each element in Chrome Dev Tools too, which is now on Blink, and it’s still the same. It’s funny though. For sure, the text in The UA stylesheet for tables differs from browser to browser. For example, in Firefox (here’s 3.6’s UA Stylesheet, but this is true in v23 too) table cells have this: Most notably, 1px of padding that WebKit doesn’t have. Not a huge deal in most cases, surely, but it is different. That’s what CSS resets (and related
projects) are all about: removing the differences. So let’s check those out. The most popular CSS reset in the world, the Meyer Reset, does this to tables: It’s done the same way in the HTML5 Reset and the
HTML5 (Doctor) Reset Stylesheet. There is an alternative to CSS resets though, Normalize.css. The philosophy is slightly different. Rather than zero out all styles, it specifically sets known-to-be inconsistent styles to a reasonable default. My general advice on using Normalize.css is: don’t remove anything from
it. If it’s in there, it needs to be for consistency. But feel free to change anything in there. Normalize only does this to tables: I’ll have to dig into the reasoning here a little deeper because it seems unusual… Not a hugely big deal. This is the kind of thing I would probably normally do: Check out this rather awkward bit of HTML: This may be weird to look at, but it’s valid. What’s going on here? If we inspect the rendered table in the browser, we can see that the tags that were missing their closing tags are shown with closing tags. Those are automatically added for us. But there are also some brand new elements in there: One thing to notice is the Then: You would think the second cell would be red, not the first, because the “first” colgroup only affects the
second cell. But when rendered, both of those columns get wrapped in a colgroup, so the CSS selector will select the first one. The You can actually use these elements in CSS selectors even though you didn’t put them in your actual HTML. I probably wouldn’t advise it just because that’s weird, confusing, and styling tag selectors usually isn’t advisable anyway. A situation may arise someday where you need to force a table element to not exhibit its table-style layout behavior and behave
more like a regular element. The trick is essentially to reset the display property of the table cells: We can pretty quickly un-table a table: Just to be safe, I’d reset the whole she-bang. Just makes me feel better knowing parent elements are also along for the ride and won’t get freaky. This is primarily useful in responsive design where the traditional table layout makes sense on large screens but needs significant shifts to make sense on smaller
screens. There is a whole section on that below. We already talked about the problems with using tables for layout and accessibility. But assuming table is being correctly used for tabular data, there are still quite a few accessibility concerns. There are some great articles on this out there: If you don’t set a background-color on the table cell elements, you can
set them on the table rows themselves. So at the most basic, you can do: We’re using the tbody in the selector because it’s unlikely you’d want to stripe header and footer rows. Set the even rows as well if you want to be specific about it instead of let what is underneath show through. If you need to support browsers that don’t understand :nth-child() (pretty damn old) you could use
jQuery to do it. Studies seem to show that zebra stripping in generally a good idea. Hightlighting a particluar row is fairly easy. You could add a class name to a row specifically for that: Highlighting
a column is a bit trickier. One possibility is to use the A table with four columns in each row would have four Then you could highlight a particular one, like: However this is rarely useful. If
you set the background of a row element or table cell element, that will always beat a background of a column element. Regardless of specificity. You’re probably better off setting a class name on each individual table cell element that happens to match that column position in the row. Like: Cell highlighting is very easy. You can do it right in CSS: Row highlighting is just as
easy. You can set the background on table rows and it will show as long as you don’t set a background on the table cells. If you do set a background on the table cells, you can always just to Column highlighting is tricker. You can’t use I wrote it up in Vanilla JavaScript here, just
for fun: It works like this: And here I’ve combined both row and column highlighting. I used jQuery to
make it all 12 lines of code (the raw JavaScript was getting pretty exhausting). It’s the same concept, it’s just much easier to make element collections, and find and select by indexes in jQuery. Some depth, visually distinct headers, and a terminal matching the header. When the table is hovered, only the current row highlighted stays dark text, the others fade back. Also note on this one: the roundered corners on the
table itself are only possible while you have Here’s another where the non-hovered rows literally blur: Twitter Bootstrap has very minimal table styling: This one, as a bonus, has keyboard control! I’m trying to keep a collection of well-designed tables for reference. So if you have any good ones,
let me know. Hong Kiat also has a blog post collection. Where table sorting can be quite complicated, table search can be quite easy. Add a search input, and if the value in there matches text anywhere in a row, show it, and hide the others. With jQuery that might be as easy as: Here’s a take with
RegExp instead: And here’s on in raw JavaScript: I’ve written about this in the past, and I think this graphic kind of sums up the experience of a data table on a small screen: I ultimately created a roundup once a variety of interesting solutions came around. Real quick though: Here’s a couple of styled live demos with different takes: This is another thing I’ve written about in the past as well as done a little screencast. Those are fairly old, but
the demo still works. The most modern way of handling fixed headers is Here’s a live demo of a jQuery plugin that does the trick. I’d probably go for something like this these days until sticky shakes out more. Emmet is a great tool for
a bunch of reasons. One of which is writing HTML abbreviations and having them expand out into real HTML. Since tables are so repetitive and verbose, Emmet is perfect for them. Emmet works on CodePen too =) Simple four rows and four columns Five rows with the header on the left A row of headers on the top Employees
with incrementing IDs Table with header, footer, and content Same but with cell content in each cell JavaScript provides some very specific methods for dealing with tables through the Here’s that at work: Imagine a table with two columns. One for Employee ID’s and another for Employee Email Address. There are headers for each column. It
would be handy to be able to click those headers and sort the table by the data inside. For instance, numerical order, alternating between ascending and descending, for the ID’s and alphabetical for the email addresses. That’s what table sorting is all about. Making the data more useful. This is such a common and generic need, that there is actually specification ready for it. Just put the At the time of this writing, I don’t know of any browsers supporting table sorting natively. But there are lots of third-party options! What’s with table sorting scripts and lowercase? Anyway, here’s a demo of tablesorter: If those don’t do it for you,
Codrops rounded up 33 different table sorting scripts, so there are plenty to choose from. And those are all JavaScript solutions. It’s certainly possible to sort data on the back-end and display the table already sorted in the HTML. That might be required in the case of paginated tables where all the data isn’t available right in the DOM. |