0

I am trying to select a previous sibling in CSS using the class name of its following sibling and I am struggling to figure it out. My objective is to remove the bottom-margin from the title element via the h1-no-margin class

body,
html,
h1 {
  margin: 0;
  padding: 0;
}

.container {
  width: 100%;
  height: 200px;
}

.container h1.title {
  margin-bottom: 2.5rem;
}
<!-- I cannot edit the HTML for the container class -->
<div class="container">
  <!-- I cannot edit the HTML for the title class-->
  <h1 class="title">This is a title</h1>
  <!-- I can edit the HTML for the below div, so I can add and remove classes on it -->
  <div class="info h1-no-margin"></div>
</div>

.

Few things to note:

  • I don't have access to any JavaScript
  • I don't have access to certain parts of the HTML
  • I haven't had any success on other solutions presented on SO

Here is the HTML:

<!-- I cannot edit the HTML for the container class -->
<div class="container"> 
  <!-- I cannot edit the HTML for the title class-->
  <h1 class="title">This is a title</h1>
  <!-- I can edit the HTML for the below div, so I can add and remove classes on it -->
  <div class="info h1-no-margin"></div> 
</div>

Here is the CSS:

body, html, h1 {
  margin: 0;
  padding: 0;
}

.container {
  width: 100%;
  height: 200px;
}

.container h1.title {
  margin-bottom: 2.5rem;
}

The idea behind this is that I can use the h1-no-margin class on the div with the info class to add and remove the margin on different pages.

Any help would be appreciated, thanks.

blueprintchris
  • 1,053
  • 1
  • 16
  • 38
  • 1
    Does this answer your question? [Is there a "previous sibling" selector?](https://stackoverflow.com/questions/1817792/is-there-a-previous-sibling-selector) – Byscripts Feb 17 '21 at 15:27
  • No, it doesn't, hence why I asked the question @Byscripts – blueprintchris Feb 17 '21 at 15:28
  • Use negative margin like this: `.h1-no-margin { margin-top: -2.5rem } ` – Andrew Feb 17 '21 at 15:32
  • In this instance, you can use negative margin to effectively hide h1.title's margin `.h1-no-margin { margin-top: -2.5rem; }` – franklylately Feb 17 '21 at 15:32
  • have you tried setting a negative margin-top margin to *swallow* the bottom margin of the previous sibbling sitting on top ? – G-Cyrillus Feb 17 '21 at 15:33
  • If someone didn't close the question then maybe one of you guys could have posted it as an answer as the suggested thread didn't have what I'm looking for – blueprintchris Feb 17 '21 at 15:33
  • Unfortunately , previous sibbling or parent selector question get closed before any valuable answer can be given , sometines those *impossible* are not needed. I understand the frustration .. – G-Cyrillus Feb 17 '21 at 15:36

0 Answers0