简体   繁体   中英

How do I apply only horizontal cell spacing to a HTML table?

I recently found out that I need to use the cellspacing attribute in my table, but I was wondering if I could get it to work only horizontally. I don't want it to vertically spread out, that messes up the layout of my entire page.

A better way than setting cellspacing="10" is to use CSS. You can use the following CSS to target the table's cell spacing.

table {
  border-spacing: 10px 0;
}

The first value specifies the horizontal spacing, and the second value specifies the vertical spacing.

If you just need to set cell contents apart, use spacing inside cells (and set cellspacing=0 in HTML). This is universally supported by CSS-enabled browsers.

If you really need to separate the cells themselves, so that there is spacing between their borders or their colored background, then border-spacing would solve the problem, but only in supporting browsers.

Depending on the context, you might even consider simulating cell spacing by putting cell contents in a div , set to cover the cell area except desired padding, which will then look like cell spacing. You would then set any desired border or background on those div elements.

Yeah, I know it's ugly and abhorrent to the separation of content and styling, but adding spacer (invisible) columns seems the only thing that consistently works across all platforms.

Here I put some empty table data in the first row and gave them a width (in pixels). I made corresponding empty table data in the successive rows. It feels real old school , but it's simple and works.

<table>
    <tr>
        <td>some content for column 1</td>
        <td width="18" />
        <td>other content for 2nd visible column (actually column 3)</td>
        <td width="18" />
        <td>content for 3rd visible column (actually column 5)</td>
    </tr>

    <tr>
        <td><img src="image_for_column 1.png" /></td>
        <td />
        <td><img src="image_for_column 2.png" /></td>
        <td />
        <td><img src="image_for_column 3.png" /></td>
    </tr>

</table>

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