Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS styling for every second div in a list

Tags:

css

I have div boxes on my website. Every second box should have a border in another color.

In one case the divs appear as a list. I cannot change the HTML code because it is automatically generated. On the other parts of my website I do the styling like this and it works:

.displayBlogpost:nth-child(2n+1) {
    border: #B4C556 1px solid;
}

But with the ol that does not work anymore. I have no idea how to get access to every second .displayBlogpost-div. This is my code: http://jsfiddle.net/8SbbL/

like image 881
Katy Avatar asked Dec 04 '12 21:12

Katy


People also ask

How do I target every other child CSS?

The :nth-child(odd) property will target every other item of the element you have selected.

How to select specific child element in CSS?

The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.

How to use child in CSS?

The child combinator ( > ) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the direct children of elements matched by the first. Elements matched by the second selector must be the immediate children of the elements matched by the first selector.


2 Answers

The element is within an li, so it is always the first and last element. Use the n-th child trick on the actual li.

#searchresult li:nth-child(2n+1) .displayBlogpost {
    border: #B4C556 1px solid;
}

Working fork: http://jsfiddle.net/FJuzm/

like image 151
circusdei Avatar answered Oct 28 '22 19:10

circusdei


to make use of the nth-child you need to apply it to the list item,

http://jsfiddle.net/8SbbL/6/

you can also use nth-child(even) and nth-child(odd) which reads nicer than your 2n-1

like image 40
Oliver Atkinson Avatar answered Oct 28 '22 20:10

Oliver Atkinson