I am trying to apply margin-top on .leaf class but margin also apply to its parent i want to apply margin-top to .leaf class only?

Viewed 31

I am trying to apply margin-top on .leaf class but margin also applies to its parent I want to apply margin-top to .leaf class only?

<!DOCTYPE html>
<html>

<head>
    <title>Page Title</title>
    <style>
        .tree {
            height: 400px;
            width: 400px;
            background-color: red;
        }

        .leaf {
            height: 30px;
            width: 30px;
            background-color: yellow;
            margin: 10px;
        }
    </style>
</head>

<body>

    <div class="tree">
        <div class="leaf" style="margin-top:100px"></div>
    </div>

</body>

</html>

3 Answers

You can use overflow: hidden; in your parent div in this case.

.tree {
    height: 400px;
    width: 400px;
    background-color: red;
    overflow: hidden;
}

.leaf {
   height: 30px;
   width: 30px;
   background-color: yellow;
   margin: 10px;
   margin-top: 100px;
}
<!DOCTYPE html>
<html>

<head>
    <title>Page Title</title>
</head>

<body>

    <div class="tree">
        <div class="leaf"></div>
    </div>

</body>

</html>

You can use position relative:

.leaf {
  position: relative;
  top: 100px;
  height: 30px;
  width: 30px;
  background-color: yellow;
  margin: 100px 10px 10px 10px;
}

The margin does not affect the child's position in relation to its parent, unless the parent has padding, in which case most browsers will then add the child's margin to the parent's padding.

Then add some padding to your parent element

 .tree {
            height: 400px;
            width: 400px;
            background-color: red;
            padding:1px;
        }

But if you don't need to apply padding for the parent element, put &nbsp; before the child element.

Full Answer

<!DOCTYPE html>
<html>

<head>
    <title>Page Title</title>
    <style>
        .tree {
            height: 400px;
            width: 400px;
            background-color: red;
            
        }

        .leaf {
            height: 30px;
            width: 30px;
            background-color: yellow;
            margin: 10px;
        }
    </style>
</head>

<body>
<div>
    <div class="tree">&nbsp;
        <div class="leaf" style="margin-top:100px"></div>
    </div>
  </div>
</body>

</html>
Related