CSS for when there are two elements

When there are two of the same elements present in the following HTML markup, I want to style them using (S)CSS without relying on JavaScript for counting and applying additional classes.

I am looking for a solution within CSS/Sass that allows me to target both instances of the element when there are exactly 2 of them.

div {
  a + a {
    // Styles should be applied to both 'a' tags, not just the second one
    // Only if 2 'a' tags exist
  } 
}
<div>
  <a href="/">Home</a>
  <a href="/about">About</a>
</a>

Answer №1

If you need to style elements that appear exactly TWO times...

a:nth-last-child(n+2):nth-last-child(-n+2):first-child, 
a:nth-last-child(n+2):nth-last-child(-n+2):first-child ~ a {

}

Check out the resource at:

a:nth-last-child(n+2):nth-last-child(-n+2):first-child,
a:nth-last-child(n+2):nth-last-child(-n+2):first-child~a {
  color: red
}
<div>
  <a href="/">Home</a>
  <a href="/about">About</a>
</div>

<div>
  <a href="/">Home</a>

</div>

<div>
  <a href="/">Home</a>
  <a href="/about">About</a>
  <a href="/more">More</a>
</div>

Answer №2

UPDATE: Initially, the question mentioned "2 or more of the same elements exist," but was later revised...

You can achieve it as shown below:

a:first-child:nth-last-child(n + 2),
a ~ *{
  color:red;
}
<div>
  <a href="/">Home</a> <a href="/about">About</a>
</div>
<div>
  <a href="/">Home</a> <a href="/about">About</a> <a href="/">Home</a> <a href="/about">About</a>
</div>
<div>
  <a href="/">Home</a>
</div>

Alternatively, you can also do it like this:

a:not(:only-child){
  color:red; 
}
<div>
  <a href="/">Home</a> <a href="/about">About</a>
</div>
<div>
  <a href="/">Home</a> <a href="/about">About</a> <a href="/">Home</a> <a href="/about">About</a>
</div>
<div>
  <a href="/">Home</a>
</div>

Answer №3

Are you utilizing a pre-compiler?

div a:nth-child(n+2) {
  background: red
}
<div>
  <a href="/">Home</a>
  <a href="/about">About</a>
</a>

If using Scss, the code below should be effective

div {
   & a:nth-child(n+2) {
    // css instruction
  } 
}

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

To avoid truncation issues, consider inserting a plus sign following the ellipsis in the text-overflow property

Hey there! I have a table that contains some text and I'm looking to shorten the text after it reaches a certain length. I was able to achieve this using the text-overflow property. .overflow { width: 70px; overflow: hidden; text-overflow: elli ...

Tips for using a button to update data without triggering a postback

Within the GridView in my ASP.net project, I have an ASP.net button with the following code: <asp:Button UseSubmitBehavior="false" runat="server" ID="btnShow" CssClass="btnSearch" Text="View All" CommandName="ViewAll" OnCommand="btnShow_Command" Comman ...

Tips for implementing events with AngularJS Bootstrap Colorpicker

I am having trouble understanding how events function with Angular Bootstrap Colorpicker. I have forked a Plunker from the developer's example. Unfortunately, there are no examples provided for using events. It would be great if events like colorpick ...

Storing Data in Web Browsers: HTML5's localStorage, Cookies, and

After browsing through numerous search results on SO, it seems that HTML5's localStorage feature is particularly advantageous compared to Cookies for storing large amounts of data that doesn't need to be sent to the server. (Local Storage vs Cook ...

What is the best way to create panels with a set height in bootstrap?

This is an example image I want to use: Is there a way to set a fixed height for all my bootstrap panels? <div class="col-md-3 padding-0"> <div class="panel panel-default"> <div class="panel-body" style="min-height: 10px; max-height ...

Using Web SQL always seems to throw me for a loop

I attempted to populate a web SQL database with some data, but encountered an issue. Here is my code: database(); for(var i=0; i<m.length; i++){ showid = m[i].id; showtitle = m[i].title; insert(); } function database(){ //open the database ...

The HTML/CSS authentication system is experiencing technical difficulties and is not functioning as intended

I came across this code on codepen.io and tried to implement it using the provided HTML and CSS. However, I encountered some errors during implementation. While the code works perfectly in the CodePen compiler, it doesn't seem to be error-free. One i ...

Optimizing Safari for the Best Screen Size Experience

I seem to be encountering issues with optimizing my website. Everything appears to be working correctly in terms of widths, heights, margins, etc., on my laptop. However, when I view the site on an iMac or any other computer with a larger screen size, the ...

Assistance is needed with the @font-face; it is not functioning correctly

I just finished creating this test document <h1> test <h1> After that, I experimented with CSS3 and wrote the following code @font-face { font-family: 'hello'; src:url('/fonts/HelloStockholm-Alt.otf') font-style: normal; ...

Use jQuery Flipclock to display duplicate print text within an interval function

I am currently utilizing jQuery Flipclock The functionality is good so far. However, I have a button to modify the time. When clicked, the time should change to 10 seconds and display the new value in the span tag. But for some reason, the old counting va ...

Strategies for Implementing Multi-Step Password Form Validation

Currently, I am using https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_form_steps as the foundation of my form with some adjustments. Validation is functioning correctly where empty fields disable the next button. However, when I attempt to add ...

Tips for creating a more flexible HTML container and resizing the navbar for mobile devices

In my current HTML code, I have 3 "col-md-4" divs within a row, each with a container--wrap to fill the webpage with 3 equally sized containers. These divs are placed inside another div with class = container-fluid. When I resize the window, the containers ...

Encountering an issue when passing an object during the creation of dynamic HTML

I am dynamically generating HTML for a bootstrap Modal and attaching it to the body element as shown below. Modal HTML function GenerateConfirmationModalHTML(HeaderMessage, Message,YesEvent, Noevent) { var html = '<div id="clearModal"> ...

Creating a receipt program in Python and protecting previous data from being overwritten

I am currently learning Python and attempting to create a program that generates an invoice listing all items, along with their prices and quantities. Each item should be displayed on a separate line. While I have managed to print each item in a line, I a ...

Include a flexible div in the hero section and change the position when resizing the screen

Looking to achieve a specific layout with only two resolutions in mind (767px minimum and maximum). For screens larger than 767px, display two divs side by side: one with text on the left and the other with an image on the right. The text remains in a fi ...

Screen resolution in HTML refers to the number of pixels

I am facing an issue with pixel positioning on my web page. I have a cover image set as the background of the body and a button placed on top of it. However, when the page is resized, the button moves along with it. I want the button to remain in its ori ...

Stop input-group-append from causing adjacent input-groups to shift right

When I have two input fields next to each other and render a button within an input group, the button pushes the neighboring input field on the right, decreasing its width. This behavior can be observed in this example sandbox: view code sample. To illus ...

Strategies for iterating through a collection of responses once and showcasing exclusively the incorrect ones

Let's consider the following as the correct and incorrect answers for each question: Question Number: 1 Correct Answer(s) B Incorrect Answers A C D Question Number: 2 Correct Answer(s) A C Incorrect Answers B D Question Number: 3 Correct ...

Mega Dropdown Menu using CSS

I am currently working on a dynamic mega drop-down menu using only HTML and CSS. The issue I'm facing is that when I select one of the list items (LIs), it expands in size at the expense of the other LIs. I'm not sure where the problem lies, so ...

Ways to insert additional panels prior to and after a selected panel

A button is provided in the report designer detail band that, when clicked, should add new panels immediately before and after the detail panel. $parentpanel = $this.parents(".designer-panel:first"); This code snippet is used to locate the parent panel u ...