How to hide element label by element id in CSS?

2019-02-06 05:51发布

问题:

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?

回答1:

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;}


回答2:

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

label[for="foo"] { display:none; }


回答3:

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:

You have to give a separate id to the label too.

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

#foo_label {display: none;}

Or hide the whole row

<tr id="foo_row">/***/</tr>

#foo_row {display: none;}


回答5:

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



回答6:

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



回答7:

This is worked for me.

#_account_id{
        display: none;
    }
    label[for="_account_id"] { display: none !important; }


回答8:

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.



标签: css input label