Reputation: 707
I have an issue with the margin-top property in CSS. I want to have an image inside a div, that's inside another div to have a 20px top margin. I tried the following:
[Css code]
* {
margin: 0 auto;
padding: 0;
}
div.wipbox {
margin-top: 20px;
width: 200px;
height: 200px;
border: 1px solid black;
}
I excluded the styling of all the other objects, unnecessary in this context.
[Html code]
<html>
<head>
<link rel="stylesheet" type="text/css" href="pagestyle.css">
</head>
<body>
<!-- "mainbox" is the box where "wipbox" is placed in -->
<div class="mainbox">
<div class="wipbox">
<img src="workinprogress.jpg" width="200" height="200">
</img>
</div>
</div>
<a class="buttonlink" href="http://www.ysbakker.eu/beta">
<div class="buttonbox">
<p class="betatext">
Click for beta
</p>
</div>
</a>
</body>
</html>
So, whenever I try to set the margin-top property to 20px, it won't show. I also found out that it will for some reason set the margin-top property of the div "mainbox". Anyone knows what to do? My website is here.
Thanks!
Upvotes: 1
Views: 1846
Reputation: 240888
Seems like a collapsing margin(s) issue:
Box model - 8.3.1 Collapsing margins.
In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.
In this instance, you could add overflow:hidden
to the parent div
element in order to fix it:
This will work.. I tested it in the dev tool.
div.mainbox {
overflow:hidden; /* Added */
width: 500px;
height: 500px;
border: 0px solid rgb(0,0,0);
margin-top: 20px;
background-color: rgba(255,255,255,0.5);
border-radius: 30px;
-webkit-border-radius: 30px;
box-shadow: 10px 10px 5px rgba(50,50,50,0.5);
-webkit-box-shadow: 10px 10px 5px rgba(50,50,50,0.5);
transition: background-color 1s;
-webkit-transition: background-color 1s;
}
Upvotes: 4
Reputation: 324620
This is normal behaviour, something to do with margin collapsing.
To "fix", try using padding-top
on the container, rather than margin-top
on the content.
Alternatively, you can add padding:0.01px
to any element to prevent margin collapsing in it.
Upvotes: 3