1

The CSS property caption-side allows you to align the <caption> element to either the top or bottom of a table: https://developer.mozilla.org/en-US/docs/Web/CSS/caption-side

How can I set the caption to appear on both the top and bottom? This could be useful for larger tables.

Ideally I would like to avoid putting a <p> tag or similar above the table and effectively duplicating the caption mark-up.

David Pratt
  • 703
  • 7
  • 16

3 Answers3

1

This is not possible with just HTML and CSS without duplicating the caption content.

Depending on your use case, you want either the caption (along with the table header and/or footer) to remain visible when scrolling, the caption to appear at the bottom of a table large enough for the caption to disappear from the top, or the caption to always appear twice. The first two require JavaScript (and especially in the case of the former some pretty heavy DOM and layout manipulation), and the third is only possible by duplicating the caption content (with JavaScript if you prefer not to pollute your markup) and putting the duplicate outside of the table, because Firefox is unable to render more than one table-caption per table due to a bug.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • I had a feeling that this might be the case. My requirement hadn't considered scrolling, but probably ultimately would. Right now my interest was in a replicated caption above and below the table. – David Pratt Feb 16 '18 at 16:51
1

table:after {
   content: attr(title);
   background-color: #333;
   color: #fff;
}

table:before {
   content: attr(title);
   background-color: #333;
   color: #fff;
}
<table title="O caption, my caption!">
  <tr>
   <td><a href="https://css-tricks.com/css-content/">CSS Tricks</a></td>
   <td>some text</td>
 </tr>
</table>

Not quite what you asked for, as there is now no <caption> element. But the caption text only appears once in the code.

Yvonne Aburrow
  • 2,602
  • 1
  • 17
  • 47
  • I like this solution, but I don't think you can use markup within the `title` attribute. – David Pratt Feb 16 '18 at 16:48
  • it works if you run the code snippet. Oh - you need to format part of the caption differently than the rest? There might be a way of only formatting part of it with CSS. – Yvonne Aburrow Feb 19 '18 at 09:21
  • CSS3 allows you to specify the format of attributes starting with, containing, or ending with a specific string http://www.css3.info/preview/attribute-selectors/ (but it's not a substring-after or substring-before function) – Yvonne Aburrow Feb 19 '18 at 09:27
  • you can format the whole `content` using CSS though. – Yvonne Aburrow Feb 19 '18 at 09:29
0

add in your HTML file:

<p id="lblCaption">YOUR CAPTION HERE</p>

add in your CSS file:

#lblCaption { position: fixed; }