Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

different style for continuous css class

I'm trying to have different css styles for a div that has same css class in a row and different for a single div for the same class.

Here's what I'm trying to achieve if the explanation is confusing.

.row {
  display: flex;
  margin: 20px;
}

.number {
  width: 32px;
  height: 32px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.number.bg {
  background-color: #e24381;
  color: #ffffff;
  border-radius: 24px 0 0 24px;
}

.number.bg ~ .number.bg {
  border-radius: 0 24px 24px 0;
}
<div class="row">
  <div class="number">1</div>
  <div class="number bg">2</div>
  <div class="number bg">3</div>
  <div class="number bg">4</div>
  <div class="number">5</div>
  <div class="number">6</div>
  <div class="number bg">7</div>
</div>

This should be the output:

Output

Can it be done by CSS only or does it require JavaScript too?

like image 417
Tushar Khatiwada Avatar asked Apr 16 '19 13:04

Tushar Khatiwada


People also ask

How do I target a different class in CSS?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)

How do I change dynamic style in CSS?

color = "red"; you can apply the style change dynamically. Below is a function that turns an element's colour to red when you pass it the element's id . You could also use setAttribute(key, value) to set a style on an element. For example, you could set the colour of an element to red by calling element.


1 Answers

For a vanilla CSS solution, you can use a pseudo element to do this for you:

  • set border-radius: 25px to the bg element,

  • fill the border gaps in successive bg elements using a pseudo element that is positioned absolutely and stacked behind the bg elements, and shifted using a negative margin.

See demo below:

.row {
  display: flex;
  margin: 20px;
}

.number {
  width: 32px;
  height: 32px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.number.bg {
  background-color: #e24381;
  color: #ffffff;
  border-radius: 25px;
  position: relative;
}

.number.bg+.bg:before {
  content: '';
  display: block;
  background-color: #e24381;
  margin-left: -50%;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  position: absolute;
}
<div class="row">
  <div class="number">1</div>
  <div class="number bg">2</div>
  <div class="number bg">3</div>
  <div class="number bg">4</div>
  <div class="number">5</div>
  <div class="number">6</div>
  <div class="number bg">7</div>
</div>
like image 145
kukkuz Avatar answered Sep 21 '22 17:09

kukkuz