user1486133
user1486133

Reputation: 1487

Clever CSS for adjusting style based on preceding or lower elements

I am trying to write some CSS for border styles, where I cannot predict what element will come next in the page. For example:

#myDiv {
  border-top: 1px solid black;
}

button {
  border-width: 4px 0 3px 0;
  border-color: black;
  width: 100%;
  padding: 6px;
}
<section>
  <button>BUTTON</button>
</section>
<div id="myDiv">^ 4px divider comprising of 3px on the button and 1px on the div</div>

However, there is a possibility of the button being followed not by #myDiv but instead by another section that has no border.

section>button {
  border-width: 4px 0 3px 0;
  border-color: black;
  width: 100%;
  padding: 6px;
}

.otherButton {
  border: none;
  padding: 6px;
  width: 100%;
  background-color: white;
}
<section>
  <button>BUTTON</button>
</section>
<button class="otherButton">SECONDARY BUTTON NO BORDER</button>

In the above instance, you can see that my use of 3px doesn't give me the required border thickness.

Is there a way to set a style for alternating between border-bottom: 3px or border-bottom: 4px depending on whether the parent section is followed by a button or a div#myDiv? I know that there are several methods for elements + other elements but cannot figure out how to utilise them in this instance.

Upvotes: 0

Views: 34

Answers (1)

Temani Afif
Temani Afif

Reputation: 273010

I would consider a negative margin-top for mydiv

#myDiv {
  border-top: 1px solid black;
  margin-top:-1px;
}

button {
  border-width: 4px 0 4px 0;
  border-color: black;
  width: 100%;
  padding: 6px;
}

.otherButton {
  border: none;
  padding: 6px;
  width: 100%;
  background-color: white;
}
<section>
  <button>BUTTON</button>
</section>
<div id="myDiv">^ 4px divider comprising of 3px on the button and 1px on the div</div>

<section>
  <button>BUTTON</button>
</section>
<button class="otherButton">SECONDARY BUTTON NO BORDER</button>

Upvotes: 1

Related Questions