How to hide element label by element id in CSS?

2019-02-06 05:50发布

Let's say I've got this code

<table>
    <tr>
        <td><input id="foo" type="text"></td>
        <td><label for="foo">This is foo</label></td>
    </tr>
</table>

This will hide the input:

#foo { display: none;}  /* or hidden could work too, i guesss */

How do I hide the label?

标签: css input label
8条回答
做自己的国王
2楼-- · 2019-02-06 06:27

You probably have to add a class/id to and then make another CSS declaration that hides it as well.

查看更多
混吃等死
3楼-- · 2019-02-06 06:29

Without a class or an id, and with your specific html:

table tr td label {display:none}

Otherwise if you have jQuery

$('label[for="foo"]').css('display', 'none');
查看更多
啃猪蹄的小仙女
4楼-- · 2019-02-06 06:36

You should give your <tr> tag an id foo_row or whatever. And hide that instead

查看更多
放荡不羁爱自由
5楼-- · 2019-02-06 06:38

If you give the label an ID, like this:

<label for="foo" id="foo_label">

Then this would work:

#foo_label { display: none;}

Your other options aren't really cross-browser friendly, unless javascript is an option. The CSS3 selector, not as widely supported looks like this:

[for="foo"] { display: none;}
查看更多
虎瘦雄心在
6楼-- · 2019-02-06 06:40

Despite other answers here, you should not use display:none to hide the label element.

The accessible way to hide a label visually is to use an 'off-left' or 'clip' rule in your CSS. Using display:none will prevent people who use screen-readers from having access to the content of the label element. Using display:none hides content from all users, and that includes screen-reader users (who benefit most from label elements).

label[for="foo"] { 
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

The W3C and WAI offer more guidance on this topic, including CSS for the 'clip' technique.

查看更多
Rolldiameter
7楼-- · 2019-02-06 06:46

If you don't care about IE6 users, use the equality attribute selector.

label[for="foo"] { display:none; }
查看更多
登录 后发表回答