This is another example of the collapse margin
problem. According to mdn web docs,
The top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the individual margins (or just one of them, if they are equal), a behavior is known as margin collapsing. Note that the margins of floating and absolutely positioned elements never collapse.
You can read more on collapsing margin here.
The body
margin is 300px and the ul
element margin is 200px, so the margin will collapse to 300px between them as it will take the highest margin value among them.
You can give margin to either of them, not both. One of the solutions is that you can give margin to one element and padding to another element so that margin will not be collapsed.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML>
<HEAD>
<TITLE>Examples of margins, padding, and borders</TITLE>
<STYLE type="text/css">
/* as you can see I have given the top margin as 300px*/
body {
margin: 300px 0px 0px 0px;
}
/* as you can see I have given the top margin as 200px for ul*/
UL {
background: yellow;
padding: 200px 12px 12px 12px;
/* No borders set */
}
LI {
color: white;
/* text color is white */
background: blue;
/* Content, padding will be blue */
margin: 12px 12px 12px 12px;
padding: 12px 0px 12px 12px;
/* Note 0px padding right */
list-style: none/* no glyphs before a list item */
/* No borders set */
}
LI.withborder {
border-style: dashed;
border-width: medium;
/* sets border width on all sides */
border-color: lime;
}
</STYLE>
</HEAD>
<BODY>
<UL>
<LI>First element of list
<LI class="withborder">Second element of list is a bit longer to illustrate wrapping.
</UL>
<UL>
<LI>First element of list
<LI class="withborder">Second element of list is a bit longer to illustrate wrapping.
</UL>
</BODY>
</HTML>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…