Skip to content Skip to sidebar Skip to footer

Css: Margin-right And Parent Element

Is margin-right not calculated or taken into account in the following example? what happens when someone increases margin-right on .box? it has no effect. why?

Solution 1:

You have a margin: 50px declaration, which applies margins on all sides, as well as a width: 300px declaration. The values are over-constrained — since you can't expect a 300-pixel wide box to only have 50-pixel horizontal margins in a containing block whose width is greater than 300 + 50 + 50 pixels — which does indeed result in the specified value of margin-right being ignored (in the typical LTR writing mode).

Solution 2:

Here, the margin is getting collapsed. It does have a margin, but you cannot see. To make it visible, we need ti add the overflow: hidden to recalculate and show up the margin.

.outer {
  width: 500px;
  margin: 0 auto;
  background: #9CF;
  overflow: hidden;
}
.box {
  width: 300px;
  background-color: #ffd900;
  margin: 50px;
}
p {
  background: #EEA458;
}
<divclass="outer"><divclass="box"><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga ipsam quibusdam pariatur animi doloremque libero sed odio asperiores aliquam, accusamus vel voluptas iusto labore ipsa aspernatur voluptates, blanditiis. Eaque rem sapiente officiis dolores
      incidunt assumenda natus reprehenderit quisquam, perspiciatis ab nostrum eligendi deserunt, pariatur, obcaecati fuga quos sunt nemo ullam!</p></div></div>

After applying overflow: hidden to the parent, you could see the top and bottom margins too.

And since your margin-right: 50px; is lesser than 150px of the space on the right, you cannot see the right margins.

This is the current box model of the .box:

box-model

Solution 3:

If you want the background of .box to be visible, use padding instead of margin:

.outer {
  width: 500px;
  margin: 0 auto;
  background: #9CF;
}

.box {
  width: 300px;
  background-color: #ffd900;
  padding: 50px;
}

p {
  background: #EEA458;
}
<divclass="outer"><divclass="box"><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga ipsam quibusdam pariatur animi doloremque libero sed odio asperiores aliquam, accusamus vel voluptas iusto labore ipsa aspernatur voluptates, blanditiis. Eaque rem sapiente officiis dolores
      incidunt assumenda natus reprehenderit quisquam, perspiciatis ab nostrum eligendi deserunt, pariatur, obcaecati fuga quos sunt nemo ullam!</p></div></div>

Post a Comment for "Css: Margin-right And Parent Element"