Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS selector difference: element element vs element>element

Tags:

css

What is the difference between the following two CSS selectors?

From the explanation here, they sound the same?

div p{}

Selects all p elements inside div elements

div > p{}

Selects all p elements where the parent is a div element.

like image 565
Smithy Avatar asked Nov 16 '14 13:11

Smithy


People also ask

Is element selector a CSS selector?

The CSS element SelectorThe element selector selects HTML elements based on the element name.

What are difference between selectors of CSS?

and hash(#) both of them are used as a CSS selector. Both selectors are used to select the content to set the style. CSS selectors select HTML elements according to its id, class, type, attribute, etc. Id selector(“#”): The id selector selects the id attribute of an HTML element to select a specific element.

What is the difference between element selector and class selector?

Great question. HTML elements are things like <h1>, <p>, <div>, <nav>, etc. They are the building blocks of the page. Classes are names/conventions the developer includes that will go inside the angle brackets of an element and allow for more specific, or general styling in CSS or functionality in JavaScript.

What is an element type CSS selector?

A Type Selector (sometimes referred to as an Element Type Selector) matches elements with the corresponding element node name, such as <p>, <span> , and <div> tags. Type selectors are generally used to make “broad stroke” changes to the style of a site. p { /* "p" is the type selector */ margin: 0 0 1em 0; }


2 Answers

The difference is depth. What the w3schools site doesn't explain very well is that E>F only matches immediate children of E, while E F matches descendants of any depth.

Using your example CSS, consider the following HTML snippet:

<div>
    <p id="paragraph1">I'm paragraph 1</p>
    <ul>
        <li><p id="paragraph2">I'm paragraph 2</p></li>
    </ul>
</div>

The first ruleset, div p, will match both p blocks. The second one, div > p, will only match paragraph1.

like image 196
Jason Baker Avatar answered Oct 29 '22 03:10

Jason Baker


div p{} 

This one applies to all p inside div

div>p{}

This one says p needs to be a direct descendent of div

like image 41
optimus Avatar answered Oct 29 '22 03:10

optimus