Adjust the CSS property dynamically based on the quantity of items within a div container

Can CSS3 be used to style the children divs of a parent div with specific conditions, such as:

  1. If there are 3 divs, apply property x to divs 1 and 2.
  2. If there are 2 divs, apply property x to div 1.
  3. If there is 1 div, do not apply property x to it.

Is jQuery necessary for implementing this dynamic logic or can it be achieved with CSS alone?

Answer №1

.parent div {
  height: 1em;
  width: 1em;
  background: red;
  margin: 0.5em;
}
.parent div:last-child {
  background: green;
}
<div class="parent">
  <div></div>
  <div></div>
  <div></div>
</div>
<hr />
<div class="parent">
  <div></div>
  <div></div>
</div>
<hr />
<div class="parent">
  <div></div>
</div>

I believe that the issue can be resolved using only CSS.

Consider using the last-child selector: http://www.w3schools.com/cssref/sel_last-child.asp

Apply the same style to all child elements and then adjust the style for the last child element.

This way, in a scenario with 3 divs, the style will apply to the third div as the last child, and in a scenario with 2 divs, it will apply to the second child as the last one, and so on.

Answer №2

Unfortunately, achieving this with just CSS is not possible. However, a simple jQuery solution involves adding a specific class to the parent div based on the number of children it contains (e.g., 'has-3-children').

var targetDiv = $('.target-div-class');

targetDiv.addClass('has-' + targetDiv.find('.child-div-class').length + '-children');

You can then easily style elements based on this added class.

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 technique to determine the completion of the most recent AJAX call in jQuery?

On one of my pages, there are approximately 5 jQuery AJAX calls that trigger as soon as the page loads. While I am aware of the ability to monitor each AJAX call individually and determine when it finishes, is there a method to track them collectively? Thi ...

Guide to using AJAX to send a select tag value to a PHP script on the current page

Issue I am facing a problem where I need to utilize the select tag in order to choose a value and then send that value via an ajax call to a PHP script embedded within the same page. In my code, I have implemented the select tag and upon selecting a valu ...

How can I match dates in order to run the following code?

If Purchase Date is after 31/Mar/xxxx it should not calculate elap_yend, rem_days, depre_cur, cur_wdv. Also I have to calculate GST with some options that is if SGST and CGST are chosen, I should not calculate IGST else if IGST selected or marked it shoul ...

The error message InvalidCharacterError is displayed when the attempt to create a new element using the 'createElement' method on the 'Document' object fails. This is due to the tag name provided ('/static/media/tab1.fab25bc3.png') not being a valid name

Hey everyone! I'm new to using React and I decided to try cloning Netflix by following a tutorial on YouTube. However, I've encountered an issue with rendering an image in a functional component. The error message I'm receiving is as follow ...

straightforward multiple second timer

I have multiple <span class="timer">342</span> elements with different values (in seconds). I am trying to create a countdown timer for all of them by using the following code: $('.timer').ready(function() { ...

Modify the height of one or more <span> elements within a table cell

Is it possible in this scenario to automatically adjust the row height for <span class="orange">ORANGE</span>? And if there are two or more <span> elements, can the cell be split to accommodate varying heights? (You can use: display: tab ...

Revolutionary web element

My vendor provides a convenient widget creation service that allows me to access their platform, input initial search form values, save them, and then easily embed the generated script code on my website to display a product search result widget. I am int ...

The function $.ajax({}) is not recognized in the Django framework

I have been searching for a solution to this specific problem, but none of the related questions I found were able to help. There must be another reason why it's not working, but I'm finding it difficult to pinpoint the issue. Here is the code sn ...

Issues with AJAX functionality in select fields - LATEST UPDATE

I have created a form with two select fields. The first field is populated with the parents of a custom taxonomy, and the second field is populated with the children of each parent. I used AJAX to accomplish this, but it doesn't seem to be working pro ...

Why am I receiving an error message stating "undefined is not a function" when trying

I am attempting to create a popover using the Angular UI pop over feature. I have loaded my HTML and compiled it, but when I run my program and click on the star icon (where I display the popover), I receive an error stating that 'undefined is not a f ...

Error encountered when attempting to retrieve JSON data in JavaScript due to being undefined

A snippet of code that reads and writes JSON data is presented below: var info; $(function () { $.getJSON("data.json", function (d) { info = d; }); $('.btn').click(function () { info['c-type'] = $('#c- ...

Problem with Bootstrap loading state when certain input fields are required

Just starting out with Bootstrap 3 and looking to integrate the loading state button function into my form. I've set up an input field with the required option as shown below. <form> <input class="input" name="title" type="text" required / ...

Using Javascript to Trigger Events on Selection

I have a unique situation: 1) One of my dropdown's choices features various car names. 2) Another dropdown has two options: When selecting each option in the second dropdown, the following should occur: a) Choose UserInput - This action will hide ...

Bootstrap 3's Clear:Left Media Query Feature

Bootstrap is being used, and there is a div with col-xs-12, col-sm-6, col-md-4 classes. Task : To add a clear on every 1 item for col-xs-12, add a clear on every 2 items for col-sm-6, and clear on every 3rd item for col-md-4. The current code only s ...

Accessing the selected value from a drop-down list in a Window.Open using the MVC model

Within my MVC View, there is a form containing a DropDownList element: @Html.DropDownList("ddlAbb" , new List<SelectListItem>(){ new SelectListItem { Selected = true, Text = "All", Value = "-1"}, new SelectListItem { ...

Recursive PHP function to create a category tree structure

I am facing an issue while trying to create a table of categories through recursive iteration of an array. The table generation works well when the depth increases, however, there seems to be a problem with the HTML output when the depth decreases. Below ...

What are the specific constraints for CSS within web components?

<html> <style> body { color: blue; } </style> <body> <h1>Styles!</h1> <p>someone created a very general selector</p> <isolated-stuff></isolated-stuff> </body> <s ...

What causes the border to trigger the appearance of a scrollbar due to an overflow?

The first image display a scrollbar, while the second one does not. It all comes down to the .tabulator CSS class and specifically the border property. How come only a 1px border impacts the scroll feature instead of affecting the entire content? https: ...

Pause and anticipate the completion of a page loading before utilizing Angular functionality

I am currently using a MEAN stack in my program that looks something like this: view: <div class="container" data-ng-controller="HomeController"> <div class="swiper-wrapper"> <div class="swiper-slide" ng-repeat="player in d ...

Searching for and replacing text that spans across multiple nodes in HTML can be accomplished using C# programming language

Here is the HTML code to consider. The term 'response' was modified to 'reason', by removing 'sp' (<del> tag) and adding 'as' (<ins> tag), while also removing 'se' (<del> tag). <div &g ...