Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select top level children using CSS

Tags:

css

Is it possible to select all top level children regardless of their type using CSS.

<div class="parent"> <div class="top-level-1">
 <!-- CONTENT -->
</div>
<div class="top-level-2">
 <!-- CONTENT -->
</div>
<a class="top-level-3">
 <!-- CONTENT -->
</a> </div>

When I use,

.parent * {}

it selects the child elements but also elements within that child.

What I want to do is,

  1. Select ONLY the top level child elements (in the sample code above - div.top-level-1, div.top-level-2 and a.top-level-3)

  2. Classes will not be the same therefore a solution where classes are not used is preferred.

Here is the JSFiddle for better understanding: http://jsfiddle.net/Q4BBd/

like image 305
user3607282 Avatar asked May 29 '14 10:05

user3607282


People also ask

How do I select a specific child 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 do I select immediate children only CSS?

The CSS child combinator ( > ) can be used to select all elements that are the immediate children of a specified element. A combinator combines and explains the relationship between two or more selectors.

How do I select the first child of a class in CSS?

The :first-child selector is used to select the specified selector, only if it is the first child of its parent.

What are the 3 main ways we can select an item through CSS?

Simple selectors (select elements based on name, id, class) Combinator selectors (select elements based on a specific relationship between them) Pseudo-class selectors (select elements based on a certain state)


1 Answers

Use the > combinator to select only immediate children (of any type) of a top-level <div>:

body > div > * {}

JSFiddle

like image 193
George Avatar answered Oct 02 '22 01:10

George