Auto margins

Behaviour of auto margin in css

by mzcarlos

HTML

<html>
<head>

</head>
<body>

Example 1: margin-left set to auto
<div class="example parent">
<div id='child1'>
This is the children
</div>
</div>

Example 2: both margins set to auto
<div class="example parent">
<div id='child2'>
This is the children2
</div>
</div>

Example 3: over-constrained. Margin-right will be forced to auto by the user agent
<div class="example parent">
<div id='child3'>
This is the children3
</div>
</div>

Example 4: both margins and width set to auto
<div class="example parent">
<div id='child4'>
This is the children4
</div>
</div>

Example 5: child bigger than container
<div class="example parent">
<div id='child5'>
This is the children5
</div>
</div>

</body>
</html>

CSS

.parent {width: 500px; background: gray;}
.example {margin: 10px 0 20px 0;}
#child1 {
  width: 100px; 
  border:0; 
  padding:0; 
  margin-right:100px;
  margin-left: auto;
  background: red;
  }
  #child2 {
  width: 100px; 
  border:0; 
  padding:0; 
  margin: 0 auto;
  background: red;
  }
  #child3 {
  width: 100px; 
  border:0; 
  padding:0; 
  margin-left: 100px;
  margin-right: 100px;
  background: red;
  }
  #child4 {
  width: auto; 
  border:0; 
  padding:0; 
  margin-left: 100px;
  margin-right: 100px;
  background: red;
  }
  #child5 {
  width: 600px; 
  border:0; 
  padding:0; 
  margin-left: 50px;
  margin-right: auto;
  background: red;
  }