CSS ul li: Avoiding double borders
Asked Answered
J

4

13

I have a UL with

border: 1px solid grey;

it contains several LIs with

border-bottom: 1px dotted grey;

to keep the items apart visually. But now the last LI has the dotted border and the UL solid border! This looks annoying. How can I avoid that? Is there a way to put borders between LIs instead of after them?

Jigaboo answered 12/11, 2010 at 14:0 Comment(1)
Exact Dupe: https://mcmap.net/q/259135/-changing-css-for-last-lt-li-gtPruchno
D
23

CSS3 selectors can target :first-child or :last-child, like this:

ul {
    border: 1px solid grey;
}
li {
    border-bottom: 1px dotted grey;
}
li:last-child {
    border:none;
}

A working example: http://api.fatherstorm.com/test/4165384.php

Denten answered 12/11, 2010 at 14:5 Comment(2)
Oh my god, that's brilliant. Thank you.Jigaboo
note that this will cause problems in IE6 if you have to support this piece of crapColorific
M
12

A smooth solution is to use the plus (+) selector to style the list:

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>

You just add the following css:

li + li {
     border-top: 1px dotted grey;
}

You avoid adding an extra selector and are able to keep the code more clean. Though depending on your needs you might want to check browser compatibilty first.

Macrophysics answered 16/6, 2013 at 16:41 Comment(1)
FatherStorm's solution is the most common (and was my own first instinct), but this is more elegant.Leela
K
2

Use a class or the CSS3 selector :last-child to remove the last <li> border-bottom

ul li:last-child { border-bottom:0; }

or

<ul>
    <li>1</li>
    <li>2</li>
    <li class="last">3</li>
</ul>

ul li.last { border-bottom:0; }
Kissner answered 12/11, 2010 at 14:2 Comment(0)
A
1

Just add a different class to the last li which specifies to not show a border.

Angeliaangelic answered 12/11, 2010 at 14:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.