I have a ul with an id portfolioItems. What I want to do is give the first li in portfolioItems a margin-left of 0.

I've searched all over google and cannot find the right way to target the first-child.

Note: I came across these sites, along with a few others, but I was not able to get them to work. http://docs.jquery.com/Selectors/firstChild http://docs.jquery.com/Selectors/first

5 answers

This was chosen as the best answer

Assuming that you have markup like this:

<ul class="portfolioItems">

Then this JS will work:

$(".portfolioItems li:first").css("margin-left",0);
Answered about 7 years ago by Eli Cochran
  • Yeah thats the code I had but it doesnt work. My HTML: <ul id="portfolioItems"> <li class="web"> ... </li> <li class="print"> ... </li> <li class="clothing"> ... </li> </ul> My JQuery: $('#portfolioItems li:first').css('margin-left','0px'); I tried changing the Jquery code for the '0px' to 0, '0'... but none of them worked. If I take off the :first the code works. Also, the reason I dont just target the first li by its class is because I have jquery code that changes the order of the li. Stephen Cronin about 7 years ago
  • I posted my example to my server: http://elicochran.com/first-child-test.html. Give it a try. I suspect that there is something else happening with your code. For me to get the margin to change, I had to add a margin to the default <li>. Eli Cochran about 7 years ago
danwellman 5600

try $('#portfolioItems').children(':first').css('margin-left','0px');

Answered about 7 years ago by danwellman

bad post

Answered about 7 years ago by Stephen Cronin

Maybe you should try try $('#portfolioItems').children(':first').css('marginLeft',0);

I think you can't use short hand syntax with this syntax unless you using it with JSON like


Answered about 7 years ago by Reungyos Vorajenwanich

You can try $('#portfolioItems').children('li:first').css('margin-left', '0px');
It should work this way :)

Answered about 7 years ago by Bogdan Constantinescu