Skip to content Skip to sidebar Skip to footer

Css Margins: Why Does This Layout Behave This Way?

I try to teach myself some CSS currently. I have made this example-layout: The div-elements within are all 100px width plus 10px margin-left and 10px margin-right. Sums up to 120

Solution 1:

change display-inline to float

.groupdiv {
  width: 100px;
  height: 100px;
  background-color: orange;
  float: left;
  text-align: center;
  line-height: 100px;
  font-size: 3em;
  font-weight: bold;
  color: white;
  margin: 10px;
}

.wrap {
  width: 480px;
  height: 120px;
  background-color: #efefef;
}
<divclass="wrap"><divclass="group"><div>1</div><div>2</div><div>3</div><div>4</div></div></div>

Solution 2:

inline-blocks are like characters, which means spaces are counted in the width too. Remove spaces/new lines between divs to get what you what. Or switch to other layout method, like float: left.

Solution 3:

you need to understand display: inline-block; default behavior when you use inline-block <div> automatically take some space from left and right to avoid that space you need to use letter-spacing: -4px; and font-size: 0; then you will have right result see snippet

.groupdiv {
  width: 100px;
  height: 100px;
  background-color: orange;
  display: inline-block;
  text-align: center;
  line-height: 100px;
  font-size: 55px;
  font-weight: bold;
  color: white;
  margin: 10px;
  letter-spacing: 0;
}

.wrap {
  width: 480px;
  height: 120px;
  font-size: 0;
  letter-spacing: -4px;
  background-color: #efefef;
}
<divclass="wrap"><divclass="group"><div>1</div><div>2</div><div>3</div><div>4</div></div></div>

Solution 4:

onther option change your HTML

.groupdiv {
  width: 100px;
  height: 100px;
  background-color: orange;
  display: inline-block;
  text-align: center;
  line-height: 100px;
  font-size: 3em;
  font-weight: bold;
  color: white;
  margin: 10px;
}

.wrap {
  width: 480px;
  height: 120px;
  background-color: #efefef;
}
<divclass="wrap"><divclass="group"><div>1</div><!--
--><div>2</div><!--
--><div>3</div><!--
--><div>4</div><!--
--></div></div>

Solution 5:

When you transform some block element to inline or similar (inline-block) you make it sensible to typography rules (whitespaces, line-height, and something else).

A easy and fast solution for your problem is to remove whitespaces from your dom (like follows).

this article is a good resource: https://css-tricks.com/fighting-the-space-between-inline-block-elements/

.groupdiv {
  width: 100px;
  height: 100px;
  background-color: orange;
  display: inline-block;
  text-align: center;
  line-height: 100px;
  font-size: 3em;
  font-weight: bold;
  color: white;
  margin: 10px;
}

.wrap {
  width: 500px;
  height: 120px;
  background-color: #efefef;
}
<divclass="wrap"><divclass="group"><div>1</div><div>2</div><div>3</div><div>4</div></div></div>

Post a Comment for "Css Margins: Why Does This Layout Behave This Way?"