1

I am using TailwindCSS and have a nested HTML structure like so:

<div class="my-4">
  <div class="my-4">
    <!-- Some Content -->
  </div>
</div>

What I don't understand is why the inner div is placed in such a way that its border aligns with the border of the outer div and the margins which I applied overlap. However, I noticed that when I add a border around the outer div, the margins suddenly behave how i would expect: the outer div contains the elements including margins.

Here is a jsfiddle to illustrate my point: https://jsfiddle.net/1vptz5fc/

How can I get the divs to behave like they do with borders, just without adding a border?

Ralph
  • 37
  • 6

2 Answers2

0

Is would say you should use the padding py that will fix it , look:

.test {
  border: 1px solid red;
}
<script src="https://cdn.tailwindcss.com"></script>

<div class=" my-4 bg-green-500 py-1" id="parent">
  <div class="my-4">
    with py
  </div>
  <div class="my-4">
    Other Content
  </div>
</div>

<button type="button" onclick="document.getElementById('parent').style.border = 'none';">
Click Me
</button>

<div class="test my-4 bg-green-500" id="parent">
  <div class="my-4">
    with border
  </div>
  <div class="my-4">
    Other Content
  </div>
</div>

<button type="button" onclick="document.getElementById('parent').style.border = 'none';">
Click Me
</button>
Dhaifallah
  • 1,437
  • 1
  • 5
  • 19
  • But can you explain to me why the margins behave this way? – Ralph Mar 22 '22 at 23:43
  • @Ralph because when you use `my-4` on the first inner `div` it won't affect its `margin-top` value because there is no element above it and the same thing for the last inner div with `my-4` it won't affect its `margin-bottom` value because there is no element under it. – Dhaifallah Mar 22 '22 at 23:57
  • @Ralph btw you can get rid of all that `my-4` classes in inner divs and replace them with `space-y-4` in the main (parent `div`) – Dhaifallah Mar 22 '22 at 23:59
0

It seems like it's the default behaviour if there's no element between parent and child.

Margin collapsing occurs in three basic cases:

  • Adjacent siblings
  • No content separating parent and descendants
  • Empty blocks

There's a stackoverflow thread that might help you: How to disable margin-collapsing?

More information on margin collapse: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing

You can probably add display: inline-block; to get the expected results regarding the margin but you will have to adjust with other styles.