Applying borders to a single table cell when using border-collapse

和自甴很熟 提交于 2021-02-07 04:55:52

问题


I have a table with the following CSS rules applied:

table { border-collapse: collapse; }
td { border: 2px solid Gray; }

I want certain cells to have a red border, instead.

td.special { border: 2px solid Red; }

This doesn't work as I'd expect. In FireFox 3 and IE8 it looks like this:


(source: control-v.net)

In IE7 Compatibility mode (Running in IE8) it looks like this:


(source: control-v.net)

I want all four sides of the <td> to be red. How can I do this? A test case can be found here.


回答1:


Won't be possible using border-collapse. You could work around the problem somewhat though, for example by doing this:

<td class="special"><div>Two</div></td>

Then applying a style like this:

.special div {
    border: 2px solid #f00;
    margin: -2px;
}

What (hopefully) will happen is the div inside the td will expand outward by 2 pixels and cover the black border with a red border.




回答2:


There's another post on the site I read a while ago that gracefully solves this problem, but I couldn't find it. Anyway, the approach was to make the border-style double instead of solid. This works because double has a higher priority than solid. On 1px or 2px borders, the gap between the double lines doesn't appear because the lines overlap.

table { border-collapse: collapse; }
td { border: 2px solid Gray; }
td.special { border: 2px double Red; }
<table>
    <tr><td>a</td><td>a</td><td>a</td></tr>
    <tr><td>a</td><td class="special">a</td><td>a</td></tr>
    <tr><td>a</td><td>a</td><td>a</td></tr>
</table>



回答3:


Using pseudo elements:

You can use a pseudo element to achieve this.

Just absolutely position the pseudo element relative to the parent td element. Make the pseudo element fill the entire dimensions of the parent element, and then add the border to it.

Example Here

table {
    border-collapse: collapse;
}
table td {
    position: relative;
    border: 1px solid #000;
    padding: 2px;
}
table td.selected:after {
    content: '';
    position: absolute;
    top: 0; right: 0;
    bottom: 0; left: 0;
    border: 2px solid red;
}
<table>
    <tr>
        <td>One</td>
        <td>One</td>
        <td>One</td>
    </tr>
    <tr>
        <td>Two</td>
        <td class="selected">Two</td>
        <td>Two</td>
    </tr>
    <tr>
        <td>Three</td>
        <td>Three</td>
        <td>Three</td>
    </tr>
</table>



回答4:


border-collapse means the td's don't actually have some of their borders. You'll have to find some other way to do it. Giving the table a background and taking away all borders but leaving the td margins gives a nice border. Then setting a border would give an internal border, I believe. Would that work?



来源:https://stackoverflow.com/questions/1241757/applying-borders-to-a-single-table-cell-when-using-border-collapse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!