Regular CSS for FF, IE7, Opera, Safari:


#subnav li {background-color: green;}
#subnav li:first-child {background-color: red;}

CSS for IE 6 (using conditional comments):

<!–-[if IE 6]>
#subnav li {background-color: expression(this.previousSibling==null?'red':'green');}
<![endif]-->

Similar to online casino :last-child
Instead of this.previousSibling==null there should be this.nextSibling==null

 

54 Responses to Pseudoclasses :first-child and :last-child for IE6

  1. pepelsbey says:

    Осталась мелочь — заставить работать :last-child ну хоть, блин, где-нибудь 🙁

    http://www.css3.info/selectors-test/

  2. Alex says:

    В FF 2.0.0.6 работает 🙂
    В ИЕ6 с этим хаком работает :)))
    В ИЕ7 с аналогичным экспрешном наверняка (проверять лень, но с чего бы не?)

  3. Роман says:

    Да всё тут понятно… (и спасибо, кстати)
    Правда каждый раз когда IE6 тупит применять expression…
    Это не скажется на скорости загрузки страницы..?

  4. Alex says:

    Зависит от глубины прохождения по DOMу.
    Если речь о конкретном примере, то чего там тупить. Тем более что оно и проходит и отрабатывает один раз, и кэшируется.

    А вот если сделать аналог более глобальный, то ой. Я вот как раз все собираюсь сделать пост о direct/nested children ( > которые)…

  5. Del'ka says:

    Отец, отец!…

    спасибо, очень кстати!

  6. John Vance says:

    Using IE conditional expressions + expressions seems like a powerful way of fixing up many problems. Is there a reason why this is in general ignored (other than its reliance on JavaScript)?

  7. Alex says:

    There are 2 different things: cond. comments and expressions

    Cond. comments is really very powerful way to fix up many problems of IEs crazyness. I guess main reason why people don’t use it – lazyness + hope to resolve things with no such “trick”.

    Expressions, well – I guess it requires special knowledge (javascript + DOM) ;))) well, very special… Plus understanding of accessibility, to have site working if JS will be turned off. People prefer to use ready-made JS scripts and libs than to write anything by hands.

  8. Chaz says:

    A very nice little fix although I could only get nextSibling to work…

  9. Chaz says:

    That’s a good example, but more than i needed. I played a bit more and I must have missed a semi-colon or something because it’s working for previousSibling now!

  10. Alex says:

    Ah perfect 😉

    Frankly last-child is almost useless thing as it is being not supported by almost any browser ;))
    At least for now.
    But useful to set IE to his place…

  11. Dave says:

    You, sir, are an evil genius, and I SALUTE YOU! 😉

  12. Sundar says:

    Great! It saved lot of my time.

  13. arisbalis says:

    How can I use this with background image? I tried this, it doesn’t work :

    div#myDiv ul li:first-child
    {
    background: url(../1stchild.jpg) repeat-x;
    }

    div#myDiv ul li
    {
    background: url(../otherchild.jpg) repeat-x;
    }

    IE6 :

    div#myDiv ul li
    {
    background-image:expression(this.previousSibling==null?’url(../1stchild.jpg) repeat-x’:’url(../otherchild.jpg) repeat-x’);
    }

    Thanks!

    • Alex says:

      Actually the code contains the error:
      background-image: expression(this.previousSibling==null?’url(../1stchild.jpg) repeat-x’:'url(../otherchild.jpg) repeat-x’);

      If you define bg-image you shouldn’t add bg-repeat parameter there.
      Try to fix this issue, ok?
      Don’t hesitate to buzz me via my gtalk.

    • 欧阳鑫 says:

      background-image:
      expression(this.previousSibling==null?’./1stchild.jpg’:’../otherchild.jpg’);不能使用url(***),

  14. Tom Taylor says:

    Hi Alex,
    Thanks for the quick answer. I just googled ‘css last child IE6’ to see if it would work without having to load up my ‘virtua pc’ and check..
    Good and straight to the point, shame you let the spammer ‘Programming Tutorials’ actually comment with that name on here though, didn’t think it was a place where I could spam out my free links. *bookmarked*

  15. abdul says:

    hi!
    This doesn’t work for me below is the code.

    background:expression(this.nextSibling==null? none : url(../images/menu_separator.gif) no-repeat right top);

  16. Alex says:

    @abdul: I suppose you forgot quotes there. Plus check the paths to image. Don’t hesitate to contact me via IM and show your page or model.

  17. evgen says:

    спасибо большое, как раз кстати решение пришлось!)

  18. evgen says:

    а для ie8 last-child как заделать?
    знаю что не поддерживает его, а как?

  19. evgen says:

    а не получается

    в ie_style.css строка
    #subnav li { background-color: expression(this.nextSibling==null?’red’:’blue’);}

    что не так?

    так тож не получается…

  20. evgen says:

    ////

  21. evgen says:

    [if IE 8]><![endif]

  22. evgen says:

    блин не могу код вставить и показать((((

  23. Alex says:

    Так лучше в мессенджере.
    Надо DOM смотреть, так по куску не скажу ничего.

  24. AbhiShake says:

    Have an image background problem like “arisbalis”

    Checkout my beta website @ cbo.in/qqcc

    How do i get the last parallelepiped out from the footer

  25. AbhiShake says:

    In IE obviously..

  26. sudhakar says:

    i need to display a separate background image for the fiest child of a list items following is my code i have tried different combinations but does not work

    .topmenu li {background-image: expression(this.previousSibling==null?url(‘absolute/path/to/topmenu_divider.jpg’):url(‘absolute/path/to/topmenu_divider1.jpg’));}

    please advice
    thanks

    • Alex says:

      There is lack of quotes, URL (as word) is not js variable. You should use additional quotes or (even better) move your current ones)

  27. sudhakar says:

    hi alex can you provide the exact syntax
    for the 1st list item i want the background to be positioned to left and for the remaining list items at top right

    following is my code but does not work

    1.

    .topmenu li {
    background: expression(true ? “url(‘website.com/topmenu_divider.jpg no-repeat top left’)”: “url(‘website.com/topmenu_divider.jpg no-repeat top right’)”);
    }

    2.

    .topmenu li {
    background: expression(true ? ‘url(“website.com/topmenu_divider.jpg no-repeat top left”)’: ‘url(“website.com/topmenu_divider.jpg no-repeat top right”)’);
    }

    • Alex says:

      Try this one:


      background: expression(true ? "url(http://website.com/topmenu_divider.jpg) no-repeat top left" : "url(http://website.com/topmenu_divider.jpg) no-repeat top right");

  28. sudhakar says:

    i have tried the following but the first-child is not working in ie6

    Link
    Link
    Link
    Link
    Link

    .topmenu ul li{background: expression(true ? “url(http://www.website.com/topmenu_divider.jpg) no-repeat top left” : “url(http://www.website.com/topmenu_divider.jpg) no-repeat top right”);}

    • Alex says:

      There is no UL / LI, maybe you could share URL to your current model?

      You can find my contacts in contact page if you’d prefer to not public the URL.

  29. veerender says:

    Could you kindly post the code for :last-child in IE.

    this.nextSibling==null is not working for the example you have given.

    • Alex says:

      To be honest I’d suggest to avoid using :last-child, it would be much more reliable to add a class there (using back-end or javascript). As not many browsers support last-child at all actually.

  30. Steve says:

    i need to display a separate background image for the fiest child of a list items following is my code i have tried different combinations but does not work

    .topmenu li {background-image: expression(this.previousSibling==null?url(‘absolute/path/to/topmenu_divider.jpg’):url(‘absolute/path/to/topmenu_divider1.jpg’));}

    please advice
    thanks

  31. Alex says:

    Steve, can I see your example at some URL? Try to catch me online using gTalk or Skype (username is mauzon)

  32. designer says:

    #subnav li {background-color: gray; color:#fff; height:30px;}
    #subnav li:first-child {background-color: blue; color:#fff; height:30px;}
    #subnav li:last-child {background-color: red; color:#fff; height:30px;}
    #subnav li {background-color: expression(this.previousSibling==null?’blue’:’gray’);}
    #subnav li {background-color: expression(this.nextSibling==null?’red’:’gray’);}

    this is my code am not able to use first child and last at a time it’s not working in ie 6.0

    • Alex says:

      You should use expression logics within expression.
      But I suggest you to use classes instead (at least for last-child)

  33. designer says:

    when i try to use back ground image, it’s also not working in ie 6.0 this is my code

    #subnav2 li { background-image:url(images/bg1.png); color:#fff; height:30px;}
    #subnav2 li:first-child {background-image:url(images/bg2.png); color:#fff; height:30px;}
    #subnav li {background-image: expression(this.previousSibling==null?’url(images/bg2.png)’:’url(images/bg1.png)’);}

  34. designer says:

    when i try to use back ground image, it’s also not working in ie 6.0 this is my code

    #subnav2 li { background-image:url(images/bg1.png); color:#fff; height:30px;}
    #subnav2 li:first-child {background-image:url(images/bg2.png); color:#fff; height:30px;}
    #subnav2 li {background-image: expression(this.previousSibling==null?’url(images/bg2.png)’:’url(images/bg1.png)’);}

  35. Amin says:

    div#test p:first-child {text-decoration: underline; color:red;}
    div#test p:last-child {color: #0000ff;}

    div#test p:{color:expression(this.previousSibling==null?’red’:’black’);}
    div#test p:{color:expression(this.nextSibling==null?’#0000ff’:’black’);}

    is not working
    please advice me…

    thanks & regards
    amin

  36. Alex says:

    Remove [:] symbol after P before {

  37. Gunasegar says:

    what if i use the border for first child and last child..

    .topNav li:first-child {

    border-left: none;
    position: relative;
    }
    .topNav li:last-child {
    border-right: none;
    }

    it doesnt work in ie6

    i also tried what u said but helpless.. how can i work out this..
    Help me pls..

    • Alex says:

      The best way is to forget about IE6
      Next best way is to add class for last child or to use jquery to add classes when the DOM created
      Worst way is to use :last-child pseudo class expression in CSS
      Good luck

  38. boom says:

    Another alternative way using jQuery:

    $(function(){
    $(“#nav li:last-child”).css(“border-bottom”,”1px solid #b5b5b5″)
    })

    source: http://stackoverflow.com/questions/1293369/using-last-child-in-css

  39. recaro baby car seats says:

    how to hack ie7 border-bottom css? can you help me please?

  40. Alex says:

    Recaro baby – please contact me directly using IM.
    Thank you

  41. Great trick, i never new you could do this with IE6! Good Job!

  42. shashi says:

    Hi Alex, We need your assistance

    I want to use the expression code.

    Below is the CSS code for normal and first-child
    #mini-ctlg-tabs li a.active{
    background: url(../images/tab-bg-active.gif) top right no-repeat;
    border:0px solid #fff;
    border-right:0;
    color:#333;
    padding:0px 30px 0 15px;
    text-decoration:none;
    cursor:default;
    }

    #mini-ctlg-tabs li:first-child a.active{
    background: url(../images/tab-bg-first-child.gif) top right no-repeat;
    border:0px solid #fcfcfc;
    border-right:0;
    color:#000000;
    cursor:pointer;
    display:block;
    height:27px;
    line-height:27px;
    padding:0 30px 0 8px;
    text-decoration:none;
    cursor:default;
    }

    Can you please help me with your suggestion or a similar sample code.

  43. Why all the fuss over IE6? Outside of China is a dead browser. See:

    http://www.ie6countdown.com/#list

  44. Alex says:

    Hey Peter. Can you please re-check post’s date?
    Thank you 😉