Choose the initial class that follows a particular class

Looking to style only the .box div that directly follows the .wrap class in the following code snippet. If it appears after a <p> tag or any other class besides .wrap, I do not want to target it.

<div class="wrap">
    <div class="box">Apply style to this box</div>
    <p>random</p>
    <div class="box">Do not apply style to this box</div>
</div>

I attempted to use the adjacent sibling selector, but it doesn't seem effective in this scenario.

.wrap + .box{
    background: red;
}

JSFiddle: http://jsfiddle.net/8fjuz7sm/

Using :first-child isn't an option since it may occur just once too.

Answer №1

Can you please include this code in your project:

.wrap .box:first-of-type{
    background:red;
}

Click here to see the demo.

Alternatively, you can also try using this code:

.wrap .box:nth-of-type(1){
    background:red;
}

Check out the demo here.

Answer №2

According to @Hiral's suggestion, you can choose to utilize either first-of-type or nth-of-type(1).

If for some reason you are unable to do so directly, you may consider modifying the html by adding an extra class to the specific elements where you want to implement the desired style, like shown below:

<div class="wrap">
<div class="box red">Apply style to this box</div>
<p>random</p>
<div class="box">Do not apply style to this box</div>
</div>

Alternatively, you can resort to using javascript and/or jquery to target the first element and then apply the desired styling through javascript.

  • Example of jQuery Usage

$(".wrap .box").eq(0).css("Background-color","red")

Answer №3

Check out the JSFIDDLE I modified for you: http://jsfiddle.net/8fjuz7sm/4/

To ensure compatibility with older browsers, I suggest using jQuery instead of a pure CSS solution:

Start by creating a new class:

.wrapperbox {
    background: red;
}

Next, add this jQuery code to your script:

$( ".wrap > .box:first" ).addClass( "wrapperbox" );

With this code, any HTML element within a class named wrap that contains a child with the class box will now have the wrapperbox class applied, allowing you to style it with CSS.

If you prefer not to use jQuery, you can try this alternative:

.wrap .box:first-of-type{
    background:red;
}

This will target the first child of wrap with the class box and apply your desired styles.

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

The CSS method to conceal the initial list item is proving ineffective

I'm having an issue with my WordPress theme where I want to hide only the first li element but it's hiding all of them. Here is the HTML code I'm using: <div class="nav"> <ul class="nav-tabs nav-justified"> <li class="activ ...

JavaScript function to convert a string of characters into a readable time format

Is there a way to input a string in an 'input type="time"' field in my HTML code? <label class="item item-input"> <span class="input-label">Departure Time </span> <input type="time" ng-model="heur ...

Footer is stubbornly stuck in the middle of the page, refusing to budge despite the

visit the live site here Despite setting the body height:100%, my footer continues to get stuck mid-page on certain pages such as about and contact. I have tried specifying the footer height and using position:fixed, position:absolute, and bottom:0, but n ...

Steps to vertically arrange a grid in Bootstrap

I've set up a basic grid layout using Bootstrap 5: <div class="row row-cols-1 row-cols-sm-2 row-cols-lg-3"> <div class="col border">Field1</div> <div class="col border">Field2</div> ...

Safari's CSS Hacking Problem

After testing the code below, it appears to be working on both Safari and Chrome. I am seeking a hack specifically for Safari, not Chrome .contactDiv img:not(:root:root) { margin-top:-75px; } @media screen and (-webkit-min-device-pixel-ratio:0) { ...

Angular encounters issue when retrieving CSS file while navigating to a nested route

When trying to access a child component directly in production mode (using ng serve --prod), it fails to load the CSS file as it attempts to fetch it from a nested path. For example, when navigating to "localhost:4200/doc/", the CSS Request URL is: loca ...

Triggers the request for Windows authentication when accessing a webpage on a website

Whenever I attempt to access a specific page on my website, a login screen pops up asking for my username and password. Even after entering the correct credentials and clicking OK or Cancel, the page still loads as normal. I can't figure out why this ...

Expanding scrollbar when hovered over

My goal for a landing page design is to showcase a centered logo at the top, followed by three images with borders arranged side by side, each with a bit of padding. When a user hovers over any of these images, I want the text on that image to slide to the ...

Display a modal pop-up containing HTML content

I recently started building a small website using Zurb Foundation. I have created a basic grid layout with large metro style div thumbnails (about 10 on the page). Now, I want to enhance user interaction by implementing modal windows that appear when a th ...

Ways to adjust Safari printing margins using CSS to achieve borderless printing

I am struggling to eliminate margins when printing a webpage to PDF in Safari. Despite setting the page size to 'A4 borderless' in the print dialogue, Safari on OSX continues to add extra margins around my HTML. Enabling 'print backgrounds&a ...

Is it necessary for a click handler to be triggered when clicking on a scrollbar?

Check out these HTML snippets: Jsfiddle <style> div { margin:20px; border: 30px red solid; padding: 20px; background-color:green; overflow-y:scroll; } </style> <div onclick="alert('div clicked');"> ...

When viewed on a mobile device, the page defaults to displaying the NumPad instead of the Text Keyboard in Angular

The email field in my angular app is opening a Key Pad in mobile view and I'm not sure why. <form (ngSubmit)="onSubmit()" #emailForm="ngForm"> <div class="emailaddress" style="text-align:center;" *ngIf="!showEmail"& ...

Steps for aligning an image to the right using Bootstrap Vue

I'm currently learning Bootstrap Vue and I'm trying to align an image on the right using a b-card header. The challenge I'm facing is that when I add the image, it disrupts the perfect size of the template header, causing the image to show a ...

Stop horizontal overflow of content

This unique Vuetify demo on CodePen showcases a two-column layout. The first column contains a <v-list> enclosed in a green <v-alert>. By clicking the "toggle text" button, you can switch the title of the first list item between short and long ...

Tips on creating a line break within a text box

There is a gap between the text boxesIn the first row, I used text boxes with labels. When I use a text box with a label, the text box is attached to the text box in the first row. I tried using a break line but in mobile view, there is a gap showing be ...

I struggle to format a classic HTML form dropdown menu that is populated using JavaScript

Hey everyone, I'm having an issue with styling a drop down menu that is populated by JavaScript. I've tried different things but nothing seems to be working. Any suggestions on how I can style the elements in the drop down? <form action="" me ...

Troubleshooting a Horizontal Scroll Problem

Can someone help me figure out why there is overscroll happening? I've tried adjusting the highslide- classes but adding overflow-x:hidden didn't solve the issue. Check this link for more information. ...

Changing the Size of a Youtube Video Based on the Width of a DIV Element

When embedding a Youtube video iframe, it is important to ensure that it scales according to the width of the containing div. The width of the div can vary depending on the layout of the page snippet. The aspect ratio of the Youtube video is 560/315, widt ...

What is the best way to display all the steps in a Material UI stepper when preparing a page for

I'm currently developing a React component that utilizes Material UI stepper functionality. The challenge I am facing is ensuring that the data is printable effectively. It's necessary for all steps to be expanded and printed, which goes against ...

Using a CSS pseudo-element within a PHP script does not produce the desired results

One challenge I'm facing is that I had to include the <?php ?> tag in my PHP code in order to add styles using pseudo element span:before with content: 'text' which contains translations for multiple languages. The <meta charset="u ...