简体   繁体   中英

Center Aling a Dynamic Width Table's Caption

I Have a Caption with Dynamic Width, and i Want it in the center of the table , but inline-block isnt working right, the inline make it in the center of the td , not of all the table, How can i make it in the center of the table? Here is a example of this html:

<table class="hours-table" style="width: 100%;" border="0"><caption>Title</caption>
<tbody>
<tr>
<td>1_1</td>
<td>1_2</td>
<td>1_3</td>
<td>1_4</td>
<td>1_5</td>
</tr>
<tr>
<td>2_1</td>
<td>2_2</td>
<td>2_3</td>
<td>2_4</td>
<td>2_5</td>
</tr>
<tr>
<td>3_1</td>
<td>3_2</td>
<td>3_3</td>
<td>3_4</td>
<td>3_5</td>
</tr>
<tr>
<td>4_1</td>
<td>4_2</td>
<td>4_3</td>
<td>4_4</td>
<td>4_5</td>
</tr>
<tr>
<td>5_1</td>
<td>5_2</td>
<td>5_3</td>
<td>5_4</td>
<td>5_5</td>
</tr>
</tbody>
</table>

Thanks a lot in Advance!

If you want it to be both vertically and horizontally aligned in the center, you could use the following CSS:

table { position: relative; }
caption {
    ​position: absolute;
    top: 50%;
    left: 50%;
    margin: -0.5em -10px; /* Change the -10px part depending on length of title */
}​

jsFiddle

If you only want it to be horizontally aligned (at the top of the table, you could use:

caption { text-align: center; }

jsFiddle

Edit: Here is a solution that will allow a background behind a centered caption but also create a white background behind just the text part of the caption:

HTML

<caption>Title</caption>

CSS

div { background: url('background_image.jpg') repeat; }
caption {
    text-align: center;
    background: rgba(0,0,0,0);
}
span { background: white; }

JS

$(function() {
    var caption = $('caption');
    caption.html('<span>' + caption.html() + '</span>');
    });​

jsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM