Given your constraints—that you can’t modify the existing markup or CSS for the div that has margin-bottom: 24px, and you have a fixed structure—you can use a combination of CSS and potentially a very small amount of JavaScript to achieve your desired layout. Here’s how you can approach it:
CSS-Only Approach (with some limitations)
If you still want to stick to CSS solutions while recognizing there's limited control over conditions based on previous elements, a completely reliable alternative isn't feasible without modifying the existing code (like the div with margin-bottom). However, you can explore two options:
- Overriding with a higher specificity CSS rule (Doesn’t always resolve the issue depending on content):
- You can target the "foot" div more specifically, but this only works when you want it to conditionally behave but would still not address the detection issue. Here’s an example of adding a class to the body if you know the state beforehand.
/* Assuming there are no templates to change. */
h1 + div + div {
margin-top: -24px; /* This won't change the behavior if the first div has content */
}
This approach would just check adjacent sibling relations but won't conditionally account for the first div having content.
JavaScript Solution
Since you cannot modify the existing structure or CSS for the .div with margin-bottom, a practical solution is to use JavaScript to detect the presence of content and apply or remove a class on the "foot" div based on that.
<h1>bla bla</h1>
<div>
<div style="margin-bottom: 24px">dfdfdfdf</div>
</div>
<div id="foot" style="margin-top: -24px">foot</div>
<script>
document.addEventListener("DOMContentLoaded", function () {
const previousDiv = document.querySelector("h1 + div > div"); // Select the div with margin-bottom
const footDiv = document.getElementById("foot");
// Check if the previous div has any content
if (previousDiv && previousDiv.textContent.trim() === "") {
footDiv.style.marginTop = "0"; // Reset the margin-top if there is no content
}
});
</script>
Explanation of the JavaScript Solution
- Selection: The JavaScript checks if the div following the
<h1> has a child div with content.
- Conditional Logic: If that child div is empty (i.e., it has no text), it resets the
margin-top style on the "foot" div to 0. This prevents unwanted layout issues in cases where the previous div should have affected the spacing but didn't.
Conclusion
While a pure CSS approach might not solve your problem due to the inability to conditionally style based on the presence of content in a previous sibling, using a small amount of JavaScript to enforce your styles based on content presence is an effective solution. This should accommodate both scenarios without needing to alter the original markup for the div that has margin-bottom.