"div p" or "div * p"? Do they have the same meaning or is there a difference between them?

My knowledge of the "grandchild" selector in CSS was limited until I came across this insightful article. Intrigued, I decided to experiment with it and found that it resembles the universal selector (which targets all elements).

Let's take a look at the following demonstration:

.wrap {
  width: 400px;
  height: 300px;
  margin: 50px auto;
}

.wrap * p {
  width: 400px;
  height: 100px;
  background-color: green;
  margin: 10px;
  color: red;
}
<div class="wrap">
  <div class="item1">
    <p>First</p>
    <div class="item2">
      <p>Second</p>
      <div class="item3">
        <p>Third</p>
      </div>
    </div>
  </div>
</div>

If we eliminate the * from the .wrap * p, there is no visible change.

Essentially, it behaves similarly to .wrap p (targeting parent followed by child).

Therefore, my question arises:

Is there any practical use for the grandchild selector *?

How does div * p differ from div p syntax?

Answer №1

A distinction exists.

Offspring of a main element can fall into 2 categories:

  1. Direct Offspring.
  2. Indirect Offspring.

For instance, look at the provided code snippet below:

<div>
  <em>This is direct offspring</span>
  <p>
    p is also a direct offspring.

    <span>This is indirect offspring</span>
  </p>
</div>

In the above example, <em> and <p> are direct offspring while <span> is an indirect offspring of <div>.

Offspring Selector:

In CSS, a space acts as an offspring selector. For example:

div p { ... }

The mentioned selector will target all <p> elements within <div> (both direct and indirect).

In the given code excerpt, all p elements will inherit styles.

.wrap p {
  background: green;
  color: white;
}
<div class="wrap">
  <p>Direct p of wrap</p>
  <div class="item1">
    <p>Indirect p of wrap</p>
    <div class="item2">
      <p>Indirect p of wrap</p>
    </div>
  </div>
</div>

Direct Offspring Selector:

> serves as a direct offspring selector. For example:

div > p { ... }

The above selector will choose all <p> elements that are direct offspring of <div>. This selector only looks for elements one level down in the DOM tree.

In the following snippet, only direct p offspring will receive styles.

.wrap > p {
  background: green;
  color: white;
}
<div class="wrap">
  <p>Direct p of wrap</p>
  <div class="item1">
    <p>Indirect p of wrap</p>
    <div class="item2">
      <p>Indirect p of wrap</p>
    </div>
  </div>
</div>

Now, What does * selector do?

* is a universal selector that can match any element.

Indirect Offspring Selectors:

We can include the * operator between two selectors to solely select indirect offspring. For example:

div * p { ... }

The above selector will pick all <p> elements within <div> that are indirect offspring (not direct). The * selector placed between div and p will specifically choose <p> when there is another element present between <div> and <p> (due to * being a universal selector).

In the subsequent snippet, only indirect p offspring will adopt styles.

.wrap * p {
  background: green;
  color: white;
}
<div class="wrap">
  <p>Direct p of wrap</p>
  <div class="item1">
    <p>Indirect p of wrap</p>
    <div class="item2">
      <p>Indirect p of wrap</p>
    </div>
  </div>
</div>

Answer №2

.wrap * p selects any p element within the children of .wrap

.wrap * p {
  font-size: 14px;
}
<div class="wrap">
  <div>
    <p>New Text</p>
  </div>
  <p>New Text 2</p>
</div>

On the other hand, .wrap p will only select direct children p.

.wrap p {
  font-size: 14px;
}
<div class="wrap">
  <div>
    <p>New Text</p>
  </div>
  <p>New Text 2</p>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switch Between More and Less Text - Implement Smooth Transition on Shopify Using Javascript

I recently implemented a More/Less toggle button using resources from this website. The functionality is there, but I now want to add a smooth transition effect. When the user clicks on "read more," I would like the hidden content to gradually appear, and ...

Incorporating a bottom line or border within the input field with a specified width

I have been struggling with styling an input field. I added a 1px solid #000 border around it, but now I need to include a thicker black line within the input itself. I tried using border-bottom: 5px solid #000, but that just created a border at the bottom ...

issue with mark.js scrolling to selected sections

Our document searching functionality utilizes mark.js to highlight text and navigate to the results. You can see an example of this in action here. If you search for "Lorem ipsum" -> the highlighting works perfectly, but the navigation jumps to fragments ...

Transform this color matching game into an image matching game using JavaScript and jQuery

I have a color matching game that I would like to enhance by matching background-images instead of just background-colors. However, I am facing difficulties in making this change. For instance, instead of matching the color red with the text "red," I wan ...

I am having trouble adding multiple items on different occasions - is it something to do with JQUERY

I have been working on a dynamic website that loads Firebase values into a table. However, I encountered an issue where the data does not appear when going back to the orders page after visiting another page. After some testing, I found that placing a but ...

Error in viewpoint/transformation transition on Microsoft Edge

Encountering a peculiar issue with MS Edge involving the animation of a door (a div tag) around the Y axis using the css rotateY() function in combination with perspective properties. The problem arises when transitioning an angle from a positive value to ...

Is there a way to adapt my existing navigation bar to collapse on smaller devices?

Struggling to make my navigation bar collapsible on my site designed for a class project. Wondering if this requires both HTML and CSS, or can it be achieved with just HTML since this is my first time working on responsive design. Below is the code I have ...

Pagination displays identical data on each page

When utilizing pagination in my AngularJS application to display search results fetched from an API call, I encountered an issue where the same data set appears on all pages. Here's what I have attempted: Within the Controller $rootScope.currentPag ...

Several components utilizing a popup module

I have created a modal popup example where scrolling is disabled in the background but enabled within the pop-up itself. Check out my demo here: View Demo My challenge lies in implementing a grid of images on the website: Take a look at the type of grid ...

Retrieve jQuery CSS styles from a JSON database

I've been attempting to pass CSS attributes into a jQuery method using data stored in a JSON database. However, it doesn't seem to be functioning as expected. I suspect that directly inputting the path to the JSON variable may not be the correct ...

Label for the checkbox is covering other content on the screen in 1024 x 768

Here is the JSP code snippet: <h:field path="configuredChannels" required="true" code="admin.menu.channels"> <div class="row-fluid" data-channel-checkboxes="#"> <form:checkboxes element="div class=&apos ...

Obtaining Beverage Overall with Loop

I am currently using a function to calculate the total of each drink, with a total of 5 drinks: var totalEstimate = 0; var locoCost = 0; var blackCost = 0; function calcLoco() { totalEstimate -= locoCost; locoCost = docume ...

Creating a Timeout Function for Mobile Browsers in JavaScript/PHP

Currently, I am developing a mobile-based web application that heavily relies on AJAX and Javascript. The process involves users logging in through a login page, sending the data via post to the main page where it undergoes a mySQL query for validation. If ...

Creating a dynamic input box that appears when another input box is being filled

I have a form set up like this: <FORM method="post"> <TABLE> <TR> <TD>Username</TD> <TD><INPUT type="text" value="" name="username" title="Enter Username"/><TD> </TR> <TR> <TD>A ...

I am curious to see the number of people who have made their selection

I am currently using JavaScript to alter the text value from "select" to "selected". My next step is to include the selected text in a cart. Can you please provide some guidance? Thank you in advance. PHP CODE : <a class='btn slct' href=&ap ...

Scrolling behavior in two columns with sticky positioning

Both columns have varying heights, with the left sometimes higher than the right. I want them to start scrolling down simultaneously, but when the shorter column's content ends, it should stick to the bottom of the viewport and "wait" until the taller ...

Changing the value of a user object's variable in Django

I have been working on implementing a feature that allows users to edit their personal information in a Django project using Django forms. However, after entering new values in the form and hitting enter, the user is redirected back to the main profile pag ...

I am seeking to modify the CSS of the parent component upon the loading of the child component in Angular

In my Angular blog, I have a root component with a navigation bar containing router links to create a single-page application. My goal is to darken the background around the link when the child component loads. Currently, the link highlights only when pres ...

I'm attempting to store this HTML code in local storage in order to utilize it on a new cart page, but I keep encountering an error

Here is the HTML snippet: <div class="cofefe"> <img src="photos/Shop%20-%20French%2Roast.png"> <p>Somecoffee</p> <p>15</p> <p>French ...

downloading responsive design

Using media queries to define backgrounds with separate images based on browser size: @media (min-width:1440px){div.container{background:URL('bg1440.png');}} @media (min-width:960px){div.container{background:URL('bg960.png');}} @media ...