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.
The CSS element SelectorThe element selector selects HTML elements based on the element name.
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.
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.
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; }
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
.
div p{}
This one applies to all p
inside div
div>p{}
This one says p
needs to be a direct descendent of div
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With