user3872085
user3872085

Reputation: 11

Fieldset and margin collapse

Why does it seem impossible to collapse margins on fieldset and legend ?

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  border: none;
}

fieldset,
legend,
div,
h1 {
  margin: 20px 0;
}

legend,
h1 {
  font-size: 14px;
  font-weight: bold;
}
<fieldset>
  <legend>With fieldset</legend>
  <div>No collapse</div>
</fieldset>
<fieldset>
  <div>No collapse</div>
</fieldset>

<div class="fieldset">
  <h1>Without fieldset</h1>
  <div>Collapse</div>
</div>
<div class="fieldset">
  <div>Collapse</div>
</div>

Upvotes: 1

Views: 690

Answers (2)

Beau Smith
Beau Smith

Reputation: 34367

Add this to your reset.css file:

legend + * {
  -webkit-margin-top-collapse: discard;
}

Check out this updated version of the Codepen example from the question above.

Also demo here…

Working Demo

legend,
p {
  margin: 20px
}

legend + * {
  /* comment out this line below and click Run to see the difference */
  -webkit-margin-top-collapse: discard;
}
<fieldset>
  <legend>Legend <strong>with</strong> collapsing margin below</legend>
  <p>☝🏽 margins collapsed πŸ•ΊπŸ½</p>
</fieldset>

Non-Working Demo (for comparison)

legend,
p {
  margin: 20px
}
<fieldset>
  <legend>Legend <strong>without</strong> collapsing margin below</legend>
  <p>☝🏽 margins not collapsed 😑</p>
</fieldset>

Upvotes: 1

Shishir Chauhan
Shishir Chauhan

Reputation: 34

Your HTML:

<fieldset>
  <legend>With fieldset</legend>
  <div>No collapse</div>  
</fieldset>
<fieldset>
  <div>No collapse</div>  
</fieldset>

<div class="fieldset">
  <h1>Without fieldset</h1>
  <div>Collapse</div>
</div>
<div class="fieldset">
  <div>Collapse</div>
</div>

And here is the updated CSS:

.fieldset, fieldset, legend, div, h1 {
  margin: 10px 0;
  float: left;
  width: 100%;
}

Added float and width :)

Upvotes: 0

Related Questions