first-child on form elements

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • damir
    New Member
    • Dec 2010
    • 14

    #1

    first-child on form elements

    Code:
    <div class="box-title">
                   <h3>Login</h3>
                   <label>Username:</label>
                   <input type="text" name="username" />
                   <label>Password:</label>
                   <input type="password" name="pass" />
                </div>
    I have a situation as above where there are two form elements (two imputs with labels). Now I can't make :first-child to work with form elements, neither with labels nor inputs.

    Can somebody help me with this?
  • JKing
    Recognized Expert Top Contributor
    • Jun 2007
    • 1206

    #2
    This is because the h3 tag is the first child in the example you have given.

    Comment

    • damir
      New Member
      • Dec 2010
      • 14

      #3
      Yes, h3 is the first child, but if I put
      Code:
      .box-title label:first-child{}
      it won't work. Not even with input, but if I put more h3's it works normally.

      --
      i've tested without h3 and it works normally. will have to find how to select the first label beside the elements before him.

      Comment

      • JKing
        Recognized Expert Top Contributor
        • Jun 2007
        • 1206

        #4
        Code:
        .box-title label:first-child{}
        This will only work if your structure looks like this
        Code:
        <div class="box-title">
        <label>First Child</label>
        <h3>Second Child</h3>
        </div>
        The label has to be the first nested element.

        Comment

        • damir
          New Member
          • Dec 2010
          • 14

          #5
          Ok, I got it. But how to make if labels are nested anywhere inside the div and then to select the first of them?

          Comment

          • JKing
            Recognized Expert Top Contributor
            • Jun 2007
            • 1206

            #6
            There is a couple things you can do.

            1) You can make a class and apply it to the elements you want.

            Code:
            .myclass {}
            Code:
            <div>
            <label class="myclass">This is a label</label>
            <label>This label has no class.</label>
            </div>
            2) CSS also has an nth:child pseudo class which can be used as follows
            Code:
            .box-title label:nth-child(2){}
            That would select all the second children. The only problem with this is it is not fully supported by IE.

            3) For cross browser compatibility using the nth:child selector you could use jquery to accomplish the same thing.

            Comment

            Working...