Why element with 100% width and displayed as table have right margin not work?

245 Views Asked by At

In the following code, when the row div is displayed as table and width set to 100%, the box shrinks and it seems the margin-right gets sets to nil or you can say that it doesn't show any affect.

However, When I remove width:100%,margin-right` gets applied

* {
  box-sizing: border-box;
}
.container {
  padding-left: 15px;
  padding-right: 15px;
}
.row {
  background-color: #cdecde;
  margin-right: -15px;
  margin-left: -15px;
}
.table {
  display: table;
  width: 100%;
}
.col {
  padding: 20px 15px;
}
<div class="container">
  <div class="row table">
    <div class="col">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Beatae autem minima minus eligendi, enim dicta quibusdam reiciendis veniam maiores accusamus ut, dolorum repellat, ea, odit quisquam magni dolor aliquid vero!</div>
  </div>
</div>

https://jsfiddle.net/sp30xr76/

Kindly explain the above behavior.

1

There are 1 best solutions below

0
On

You are apply negative margins to row element - this is causing the problem here:

When the negative margins are applied the table is shifted to the left taking up the space of the padding given to the container - try removing the negative margins from row and see how it nicely aligns horizontally:

* {
  box-sizing: border-box;
}
.container {
  padding-left: 15px;
  padding-right: 15px;
}
.row {
  background-color: #cdecde;
  /*margin-right: -15px;
  margin-left: -15px;*/
}
.table {
  display: table;
  width: 100%;
}
.col {
  padding: 20px 15px;
}
<div class="container">
  <div class="row table">
    <div class="col">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Beatae autem minima minus eligendi, enim dicta quibusdam reiciendis veniam maiores accusamus ut, dolorum repellat, ea, odit quisquam magni dolor aliquid vero!</div>
  </div>
</div>

When you don't give width: 100% the table takes the full available width because the content of table is a text that spans multiple lines.

See what happens when there is less text:

* {
  box-sizing: border-box;
}
.container {
  padding-left: 15px;
  padding-right: 15px;
}
.row {
  background-color: #cdecde;
  margin-right: -15px;
  margin-left: -15px;
}
.table {
  display: table;
}
.col {
  padding: 20px 15px;
}
<div class="container">
  <div class="row table">
    <div class="col">Lorem ipsum dolor</div>
  </div>
</div>

Hope that clears things up, thanks!