W3c believes that the margin stack is reasonable. Whether it is a bug or not, but this problem does exist. Let's look at the example below:
- <! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <Html xmlns = "http://www.w3.org/1999/xhtml">
- <Head>
- <Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
- </Head>
- <Style type = "text/css">
- * {Padding: 0; margin: 0 ;}
- . Box {background: # ccc ;}
- . Content {background: # eee; margin: 20px auto ;}
- . An-box {margin: 50px auto; background: #999999 ;}
- </Style>
- </Head>
- <Body>
- <Div class = "box">
- <Div class = "content"> margin: 20px auto </div>
- <Div class = "content"> margin: 20px auto </div>
- </Div>
- <Div class = "box">
- <Div class = "content"> margin: 20px auto </div>
- </Div>
- <Div class = "box">
- <Div class = "content"> margin: 20px auto </div>
- </Div>
- <Div class = "an-box"> margin: 50px auto </div>
- </Body>
- </Html>
There are many ways to solve this problem. Let's take a look at this. In the outer container, add overflow: hidden; zoom: 1;
- <! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <Html xmlns = "http://www.w3.org/1999/xhtml">
- <Head>
- <Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
- </Head>
- <Style type = "text/css">
- * {Padding: 0; margin: 0 ;}
- . Box {background: # ccc; overflow: hidden; zoom: 1}
- . Content {background: # eee; margin: 20px auto ;}
- . An-box {margin: 50px auto; background: #999999 ;}
- </Style>
- </Head>
- <Body>
- <Div class = "box">
- <Div class = "content"> here there are two overlapping margin: 20px auto </div>
- <Div class = "content"> here there are two overlapping margin: 20px auto </div>
- </Div>
- <Div class = "box">
- <Div class = "content"> margin: 20px auto </div>
- </Div>
- <Div class = "box">
- <Div class = "content"> margin: 20px auto </div>
- </Div>
- <Div class = "an-box"> margin: 50px auto </div>
- </Body>
- </Html>
In addition, the border attribute is added to the outer container, and the empty block element is added to the overlay element .. Also, we use padding to replace margin.