Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add certain CSS to middle elements?

I have something like this:

<html>
<head>
    <style>
        div {
            padding: 10px;
            border: solid 2px;
            border-radius: 10px;
            display: inline-block;
        }

        div + div {
            border-radius: 0px;
        }
    </style>
 </head>
 <body>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
 </body>
</html>

This is the output:

enter image description here

but I am trying to get this:

enter image description here

Please note there isn't any certain parent with special ID or class or even tag type; then I can't use first-child and last-child selectors.

And also, I can't use (and I don't want to use) special classes for middle elements or corners. I am just wondering to know if there is any way to have it without using classes and in unlimited number of same elements close to each other.

Thanks in advance.

like image 261
Reza Amya Avatar asked Nov 17 '25 04:11

Reza Amya


1 Answers

A hacky way with only + selector and no need nth-* selectors and it can work with any contiguous set of elements with the same type.

You may have to adjust the different values used within pseudo elements depending on the situation:

div {
  padding: 10px;
  border: solid 2px;
  border-radius: 10px;
  display: inline-block;
  position: relative;
}

div + div:before,
div + div:after {
  content: "";
  position: absolute;
  top: -2px;
  bottom: -2px;
  width: 8px;
  border: 2px solid;
  background: #fff;
}

div + div:before {
  border-left: 0;
  right: calc(100% + 4px);
}

div + div:after {
  border-right: 0;
  left: -2px;
}
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<span>--</span>

<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>

<span>--</span>

<div>1</div>
<div>2</div>

<span>---</span>

<div>1</div>

In case you will have only one contiguous set of elements with the same type within the container you can try this. The trick is to avoid the shorthand version of border-radius so that it can work with one element:

div {
  padding: 10px;
  border: solid 2px;
  display: inline-block;
  position: relative;
}

div:first-of-type {
  border-top-left-radius: 10px;
  border-bottom-left-radius: 10px;
}

div:last-of-type {
  border-top-right-radius: 10px;
  border-bottom-right-radius: 10px;
}
<section>
  <span>---</span>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <span>---</span>
</section>
<section>
  <span>---</span>
  <div>1</div>
  <div>2</div>
  <span>---</span>
</section>
<section>
  <span>---</span>
  <div>1</div>
  <span>---</span>
</section>
like image 192
Temani Afif Avatar answered Nov 19 '25 18:11

Temani Afif



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!