Home > Back-end >  I am trying to apply margin-top on .leaf class but margin also apply to its parent i want to apply m
I am trying to apply margin-top on .leaf class but margin also apply to its parent i want to apply m

Time:05-28

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 >
        <div  style="margin-top:100px"></div>
    </div>

</body>

</html>

CodePudding user response:

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 >
        <div ></div>
    </div>

</body>

</html>

CodePudding user response:

You can use position relative:

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

CodePudding user response:

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 >&nbsp;
        <div  style="margin-top:100px"></div>
    </div>
  </div>
</body>

</html>
  • Related