0

I have created an outer div element and I am trying to make a simple rectangle inside it. Now, the horizontal positioning of the first side is spot on. However, for the vertical positioning, I want to have a margin of 10px between the top, bottom of the lenght1 div and the outer div. Below is my code.

<!DOCTYPE html>
<html>
<head>
<style>
*{
    margin:0px;
    padding:0px;

 }
 body{
    margin:10px 0px;
 }
div.outer{
    height:400px;
    width: 500px;
    margin:100px auto;
    margin-top: 130px;
    background-color:red;
 }
 div.length1{
    height:380px;
    width:30px;
    margin:10px 470px 10px 0px;
    background-color:blue;
 }
</style>
</head>
<body>
    <div class="outer">
      <div class="length1"></div>
      <div class="breadth1"></div>
      <div class="length2"></div>
      <div class="breadth2"></div>
    </div>
</body>
</html>
  • Possible duplicate of [How to disable margin-collapsing?](http://stackoverflow.com/questions/19718634/how-to-disable-margin-collapsing) – Asons Jun 20 '16 at 18:12

2 Answers2

0

Margins on the inner div's collapse, hence doesn't get pushed as expected.

It is very well explained here:

One way is to give the parent overflow: auto

*{
  margin:0;
  padding:0;
}
body{
  margin:10px 0;
}
div.outer{
  height:180px;
  width: 500px;
  margin: 0 auto;
  background-color:red;
  overflow: auto;
}
div.length1{
  height: calc(100% - 20px);
  width:30px;
  margin: 10px 0 10px 10px;
  background-color:blue;
}
<div class="outer">
  <div class="length1"></div>
  <div class="breadth1"></div>
  <div class="length2"></div>
  <div class="breadth2"></div>
</div>

Another way is to use padding on the parent instead of margin on the children

*{
  margin:0;
  padding:0;
}
body{
  margin:10px 0;
}
div.outer{
  height:180px;
  width: 500px;
  margin: 0 auto;
  background-color:red;
  padding: 10px;
}
div.length1{
  height: 100%;
  width:30px;
  background-color:blue;
}
<div class="outer">
  <div class="length1"></div>
  <div class="breadth1"></div>
  <div class="length2"></div>
  <div class="breadth2"></div>
</div>
Community
  • 1
  • 1
Asons
  • 84,923
  • 12
  • 110
  • 165
0

Use

position:absolute;

in the length1 style.

like:

.length1{
    height:380px;
    width:30px;
    margin:10px 470px 10px 0px;
    background-color:blue;
    position:absolute;
 }

You can also use .length1 instead of div.length1 :)

and I would remove:

*{
    margin:0px;
    padding:0px;

 }
 body{
    margin:10px 0px;
 }
Frazstew
  • 1
  • 2