Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this CSS :first-child selector work?

I'm working on an Asp.Net MVC 3 project and have run into a brick wall on why this doesn't work like I think it should.

My markup is:

<fieldset>
    <input type="hidden" value="2">
    <div class="editor-label"> 
        <label for="Name"> Name</label>
    </div>
    ...
</fieldset>

My css is:

.display-label, .editor-label
{
    margin: 0.8em 0 0 0;
    font-weight: bold;
    display: inline;
}

fieldset > div:first-child
{
    margin: 0;
}

All I want to do is make the first div in the fieldset have a margin of 0. I thought that the selector fieldset > div:first-child would apply the style to "the first child of a fieldset, whose type is a div", but apparently something is eluding me.

I've tried this in IE9/FF/Chrome so it's not an old browser messing with my selectors.

Thanks.

like image 503
Alex Moore Avatar asked Sep 28 '11 21:09

Alex Moore


People also ask

How do you select the first child in CSS?

The :first-child selector is used to select the specified selector, only if it is the first child of its parent.

How do you add CSS to not your first child?

This selector is used to select every element which is not the first-child of its parent element. It is represented as an argument in the form of :not(first-child) element. Explanation: The above example shows that a <div> is a container Tag.

How do I use first child and last child in CSS?

How to select an element that is the first or last child of its parent. The :first-child pseudo class means "if this element is the first child of its parent". :last-child means "if this element is the last child of its parent". Note that only element nodes (HTML tags) count, these pseudo-classes ignore text nodes.

What is a not (: first child?

ul:not(:first-child) means literally "any ul element that is not first child of its parent", so it won't match even the 1st ul if it's preceded by another element ( p , heading etc.). On the contrary, ul:not(:first-of-type) means "any ul element except the 1st ul in the container".


1 Answers

fieldset > div:first-child means "select the first child element of a fieldset if it's a div".

It does not mean "select the first div in the fieldset".

The first child in this case is <input type="hidden" value="2">.

To select that div without changing the HTML, you need to use fieldset > div:first-of-type.

Unfortunately, while :first-child is widely supported, :first-of-type only works in IE9+ and other modern browsers.

So, in this case, the best fix is to continue using fieldset > div:first-child, and simply move <input type="hidden" value="2"> so that's it's not the first child.

like image 151
thirtydot Avatar answered Sep 26 '22 16:09

thirtydot