What is the best way to target the first child element in this scenario?

Is there a way to target only the p tag with id="this" using .root p:first-child selector?

Here is the code snippet:

Link to CodePen

.root p:first-child {
  background-color: green;
}

p {
  margin: 0;
}

.container {
  display: inline-box
}

.root {
  display: flex;
}

div {
  display: block;
  background-color: pink;
  border: 1px solid red;
  width: 100px;
  height: 100px;
}
<div class="root" id="this">
                <div class="container">
                    <p>test</p>
                </div>
                <div class="container">
                    <p>test2</p>
                </div>
                <div class="container">
                    <p>test3</p>
                </div>
            </div>
            

Answer №1

The first-child selector chooses and applies styles to each element that is the initial child of its parent. In this case, the styles were applied to all <p> tags because there is only one <p> tag inside its corresponding parent .container.

Instead of targeting the first child of the p element, target the first child of the class .container to achieve the desired outcome.

.root .container:first-child p{
  	background-color: green;
}

p {
	margin: 0;
}

.container {
	display: inline-box
}

.root {
	display: flex;
}

div {
	display: block;
	background-color: pink;
	border: 1px solid red;
	width: 100px;
	height: 100px;
}
<div class="root">
  <div class="container">
    <p>test</p>
  </div>
  <div class="container">
    <p>test2</p>
  </div>
  <div class="container">
    <p>test3</p>
  </div>
</div>

Answer №2

Check out this handy css snippet:

.root p:first-child {
     background-color: green;
}

This code selects all paragraph elements that are the first child of their parent element. To target the first paragraph elements inside the first container, use this code:

.root .container:first-child p{
      background-color: green;
}

Alternatively, if you want to style the first paragraph inside both the first container and the first paragraph itself, try this:

.root .container:first-child p:first-child{
      background-color: green;
}

Answer №3

Are you searching for this? Choosing the paragraph inside the first child of the main element.

.main .box:first-child p {
  background-color: green;
}

p {
  margin: 0;
}

.box {
  display: inline-box
}

.main {
  display: flex;
}

div {
  display: block;
  background-color: pink;
  border: 1px solid red;
  width: 100px;
  height: 100px;
}
<div class="main">
  <div class="box">
    <p>test</p>
  </div>
  <div class="box">
    <p>test2</p>
  </div>
  <div class="box">
    <p>test3</p>
  </div>
</div>

Answer №4

There are various methods to select the first child based on your specific requirements. Here are a few ways to achieve that:

If you want to target the first child of the container, you can use the following CSS:

.root .container p:first-child {
  background-color: green;
}

p {
  margin: 0;
}

.container {
  display: inline-box
}

.root {
  display: flex;
}

div {
  display: block;
  background-color: pink;
  border: 1px solid red;
  width: 100px;
  height: 100px;
}
<div class="root">
  <div class="container">
    <p>test</p>
  </div>
  <div class="container">
    <p>test2</p>
  </div>
  <div class="container">
    <p>test3</p>
  </div>
</div>

If you wish to select the first child of the first container, you can utilize the following CSS code:

.root .container:first-child p {
  background-color: green;
}

p {
  margin: 0;
}

.container {
  display: inline-box
}

.root {
  display: flex;
}

div {
  display: block;
  background-color: pink;
  border: 1px solid red;
  width: 100px;
  height: 100px;
}
<div class="root">
  <div class="container">
    <p>test</p>
  </div>
  <div class="container">
    <p>test2</p>
  </div>
  <div class="container">
    <p>test3</p>
  </div>
</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

Click the 'expand' button for additional details on every row in the table

I am facing a challenge with my HTML table where I have a lot of information to add for each row. However, displaying everything at once makes the page look cluttered. Therefore, I am looking to add a "view more" button in another column for each row. Des ...

The chosen date is not preserved within the select box

I have these specific items: $scope.items = [{"date":"2014-12-26T05:00:00.000Z","display":"6:00"}, {"date":"2014-12-26T05:15:00.000Z","display":"6:15"}, {"date":"2014-12-26T05:30:00.000Z","display":"6:30"}] When I use the following code: <select ...

Button appears and disappears sporadically while browsing in Safari

I created a slider using SCSS, JavaScript, and HTML. You can view the demo at this link: https://jsfiddle.net/rr7g6a1b/ let mySlider = { initializeSlider: function (options) { let slider = options.container; let slides = slider.querySelectorAll( ...

What are the reasons for the failure of an image upload when checked with PHP's is_uploaded_file function?

My html form allows users to upload images, but I'm encountering an issue where the uploaded image fails the "is_uploaded_file" check for some unknown reason. I'm puzzled as to why the upload is failing the is_uploaded_file check. Any ideas? He ...

How can the height of a Material-UI Grid item be dynamically set to match its width?

I am trying to create grid items that are square, where the height matches the width: const App = ({ width, items }) => ( <Grid container> {items.map((v) => ( <Grid item md={width}> // I want this Grid item to be square ...

Necessary workaround needed for HTML time limit

Our HTML page has been designed to automatically timeout after 10 minutes of inactivity. This functionality is achieved through the following code: function CheckExpire() { $.ajax({ type:'GET', url:self.location.pathname+"?ch ...

Styling React components using class names

Struggling with implementing a sidebar feature using the guidance provided in this example. However, I am facing difficulty in applying the necessary styles to each className... Here's what I've attempted so far, but unfortunately, no styles see ...

Tips for executing a Python function from JavaScript, receiving input from an HTML text box

Currently, I am facing an issue with passing input from an HTML text box to a JavaScript variable. Once the input is stored in the JavaScript variable, it needs to be passed to a Python function for execution. Can someone provide assistance with this pro ...

Positioning of vertical linear gradients in CSS

Check out this live demonstration: http://jsfiddle.net/nnrgu/1/ I then adjusted the background position to 0px -70px and observed the changes here: http://jsfiddle.net/nnrgu/2/ The linear gradient seems to disappear! Am I doing something wrong, or is ...

Place the div directly beside the input field on the right side

I am attempting to align a div directly beside the text being entered in a text input field. It seems logical to me that this could be achieved by measuring the length of the input value and positioning the div accordingly. However, the issue I am facing i ...

Interested in learning how to code games using JavaScript?

Hi everyone, I'm currently exploring the world of Javascript and have been tasked with completing a game for a class project. The game involves a truck that must catch falling kiwis while only being able to move left or right. A timer is set for two m ...

To highlight errors in ASP.NET MVC4 form validation, consider adding a vivid red border around the selectize dropdownlist

I have implemented the selectize framework for my dropdown list in asp.net mvc4 and successfully modified the CSS for all form fields bound to asp.net mvc4's validation engine. However, I am facing an issue with creating a border around the dropdownl ...

Issue with Django app: Bootstrap 4 modal hidden behind background

Having exhaustively researched this issue, I am still unable to resolve it with the outdated Bootstrap solutions available. The problem arises when I click on the button - the modal appears behind the background instead of in front. Most suggestions indica ...

Shorten Text - React Native

I currently have a React Native application with a FlatList component. The logic I initially implemented was to display an Expand/Collapse arrow whenever the content at the 100th position in the list is not empty. However, I now realize that this approach ...

How can you apply styling to one element when focusing on a different element at separate hierarchy levels?

I'm currently facing a challenge with styling a text field to expand when focused, and adding an "Add" button below it. The issue is that the elements are on different levels in the code structure, making it difficult to show or hide the button when f ...

After resolving a quirky syntax error in my ejs code, I can't help but ponder what caused the issue in the first place

For my personal web development project, I've been working on a blog webpage to enhance my skills. However, I encountered an unusual syntax error while modifying the code to display different navigation bars for logged in and logged out users. Here&ap ...

Focused input filter in a tabular header style

I've been working on customizing the Tabulator header filter to have a more "flattened" style, as requested by my boss. In my CSS, I added the code ...input:focus{border:1px solid #1bb394} to change the input border to 1px green. While this change tak ...

Steps for adding a stroke to just the left and right sides of an SVG wave:

How do I apply a stroke only to the right and left sides of an SVG (specifically a wave SVG)? <svg class="defs-only" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <symbol id="wave"> <svg viewBox="0 0 100 50" ...

Can a single value be stored in a table using a radio button?

I have created an HTML table that is dynamically generated from a database. I am using a for loop to populate the table. However, I am facing an issue where each radio button in the table holds only one value. What I actually want is for each row to have ...

Using JavaScript to invoke Applescript commands

Is it feasible to execute Applescript from JavaScript? I would be grateful if someone could offer a sample code or useful reference link. ...