"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

Is there a way to access the value of a variable within a loop inside a function and store it in a global variable?

I am struggling to retrieve the value of a variable after it has passed through a loop. I attempted to make it a global variable, but its value remains unchanged. Is there any way to achieve this? Below is my code snippet where I am attempting to access t ...

Making sure to correctly implement email input fields in HTML5: Surprising behaviors observed with the email input type in the Chrome browser

Within the upcoming code snippet, a basic email validation is implemented. An input field's background color will display as white for valid emails and yellow for incorrect values. This functionality operates seamlessly in Firefox; however, in Chrome, ...

What is the best way to add a triangle pointer to the Vuetify v-menu component?

Is there a way to insert a triangular pointer into the v-menu component of Vuetify 2.x? I am referring to this common feature found on web pages (as seen in this screenshot from Github): https://i.stack.imgur.com/DMOjF.png I have included sample code he ...

Guide to setting up collapsible sections within a parent collapsible

I came across this animated collapsible code that I'm using: https://www.w3schools.com/howto/howto_js_collapsible.asp Here is the HTML: <button type="button" class="collapsible">Open Collapsible</button> <div class="content"> &l ...

Instead of stacking neatly, the Bootstrap rows are overlapping each other

I am currently working on a webpage design using bootstrap. The layout consists of different sections, each containing a bootstrap row within a container. However, I encountered an issue where new rows are not appearing below the previous row as expected, ...

Accessing a variable from another HTML using JavaScript

I'm currently attempting to access a variable from another HTML file using JS. Specifically, I have a file (file1.htm) that opens a dialog box, and I want to send the information of the selected file to another file (file2.htm) in order to modify a v ...

Is there a way to shift a button within a div to the right while maintaining alignment?

After spending hours on this problem, I attempted to use "float: right" and successfully moved the button to the right. However, in doing so, the tag is no longer vertically centered. Can someone please assist me with this? Also, if there are multiple sol ...

Retrieving the headers from an ajax request

Is there a method to retrieve the complete request headers used in an AJAX call made through jQuery? ...

Attempting to utilize jQuery for altering the background URL leads to the unexpected removal of the -webkit-background-clip:text; effect

Can the -webkit-background-clip:text; effect be preserved when using jQuery to switch the background url? I am experiencing issues where changing the URL removes the text clipping effect. jQuery(function($) { var whatToSwitch = $('.homepage_ove ...

Is a Responsive Split Layout the Solution for Your Web Design Needs?

I'm looking to create a webpage layout where the left half of the viewport is for Login and the right half is for Signup. This layout should be split side by side on tablets, desktops, and large screens, but stacked vertically (Login on top, Signup on ...

The onsubmit function encounters an issue with invocation when implemented with Node.js

When I submit the form, I want to perform some validations. However, it seems like the validation function is not working as expected. The alert part does not appear when triggered. Here is the code snippet: function validation(){ alert("somethi ...

To ensure that any changes made to data are reflected automatically when viewing data in Angular 2

In the process of developing an Angular 2 application, I encountered a scenario that requires special attention. The data displayed on the view is fetched from an API, with certain fields being editable by the user. These modifications can be saved using ...

Leverage the power of Bootstrap 4 without incorporating its pre-built components

Is it possible to utilize Bootstrap 4 without its components? The diagram below seems to suggest otherwise, correct? My Scenarios: I need to implement Angular Material components instead of Bootstrap components. It's acceptable to use Bootstrap 4 ...

Conceal the button briefly when clicked

How can I disable a button on click for a few seconds, show an image during that time, and then hide the image and display the button again? HTML: <input type="submit" value="Submit" onclick="validate();" name="myButton" id="myButton"> <img st ...

Align the text to the right within a display flex container

Below is the code snippet: <div className="listContent"> <div> <div className="titleAndCounterBox"> <div className="headerListTitle">{list.name}</div><br /> <div ...

Viewing a Google Charts graph upon the loading of a web page

Utilizing the Google Charts library, I have incorporated a graphic on my web page that is dynamically added using AJAX into a <div> element. To display the graph when the page loads, I have written the following code: <script type="text/ ...

Customizing number input types in Angular 2 - the perfect solution

Attempting to incorporate a time picker using HTML5 input type number in Angular2. The code snippet below illustrates the setup: <input type="number" [(ngModel)]="hour" (change)="checkHours();" name="one" min="1" max="12"> <input type="number" ...

Triggering a jQuery event when a CSS property is altered

My current approach involves utilizing the .animate method to shift a div 100px to the right in just 1 second. Essentially, this means moving by 1px every 10ms. I am now exploring whether there exists an event that could be triggered after each individual ...

What is the best way to insert additional text into an li element without replacing the text that is already there using

Currently, I am adding to a list and need to prepend text to an li item whenever the user clicks on a radio button. I attempted using the JQuery .text() function but found that it overrides the existing content instead of appending. $("#" + condition + "- ...

Tips for preventing elements from wrapping in a lengthy list and using scrollbars in Firefox

When dealing with a lengthy flex list, the items (buttons) should wrap when there is not enough space available (using flex-wrap). However, an issue arises in Firefox where the items are wrapped once a scrollbar appears, even if there is ample space. In c ...