First-child - how to style first element of a given type?

Suppose I have this html:

<form action="url" method="post" class="simple-search">
    <input type="hidden" name="var1" value="v1" />
    <input type="hidden" name="var2" value="v2" />

    <span class="fieldgroup">
        ...
    </span>

    <span class="fieldgroup">
        ...
    </span>

    <span class="fieldgroup">
        ...
    </span>
</form>

and I want to style the first <span class="fieldgroup">. When I do this:

form.simple-search span.fieldgroup:first-child {
    margin-left: 0;
}

it will not work because I have the input elements before the spans. Is there any way to achieve this without changing html and adding new class names?

Try first-of-type instead of first-child.

1 Like

Yes, first-of-type. But why are you using a span, which is 1) not a block level container and 2) when there’s the very handy fieldset element for grouping form elements?

1 Like

Thanks, yes it works perfectly, I’ve been a bit behind the times with css so didn’t know about first-of-type.

And I’ll probably use fieldset since it fits well semantically.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.