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.
The :first-child selector is used to select the specified selector, only if it is the first child of its parent.
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 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.
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".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With