I assumed margin
is the space between parent element and itself since long time ago. But I think it is not true. Please check below short HTML with CSS.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Box Model</title>
<style type="text/css">
body {
background-color: #ccc;
}
header {
text-align: center;
text-decoration: underline;
font-weight: bold;
}
#container {
background-color: grey;
width : 400px;
height : 400px;
}
#container .box {
background-color: slategrey;
width : 200px;
height : 200px;
color : #fff;
border: 5px solid navy;
margin-top: 50px;
margin-left:50px;
padding-top:20px;
padding-left:20px;
}
</style>
</head>
<body>
<header>Box Model Example</header>
<section>
<div id="container">
<div class="box">Content</div>
</div>
</section>
</body>
</html>
You will see the output as below screenshoot.
My margin-top:50px;
is not the space between parent elment container and element box. How could I add the space(from above) between these two elements ?
You're not wrong about what margin is. I think your actual question is "why does margin-top
not work here?".
If I'm not mistaken, this is a case of collapsing margins: under certain circumstances, vertical margins of two elements will combine. (Note how there is top margin in your example, it's just all on the outer box.)
You can try one of the solutions mentioned over there (for instance, floating the inner box), or add padding to the outer box instead.
your code is correct.
but you need add these lines to your #container & #container .box classes.
display:inline-block;
position:relative;
learn more about display & position in: http://www.w3schools.com
your final code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Box Model</title>
<style type="text/css">
body {
background-color: #ccc;
}
header {
text-align: center;
text-decoration: underline;
font-weight: bold;
}
#container {
background-color: grey;
width : 400px;
height : 400px;
display:inline-block;
position:relative;
}
#container .box {
background-color: slategrey;
width : 200px;
height : 200px;
display:inline-block;
position:relative;
color : #fff;
border: 5px solid navy;
margin-top:50px;
margin-left:50px;
padding-top:20px;
padding-left:20px;
}
</style>
</head>
<body>
<header>Box Model Example</header>
<section>
<div id="container">
<div class="box">Content</div>
</div>
</section>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With