Margin-top problem between parent element and child element (CSS hack)

Source: Internet
Author: User

hack:
The parent element's box contains a child element box, a vertical margin margin-top to the child element box, the parent element box also goes down the value of margin-top, and the margins of the child and parent elements are not changed.

<!DOCTYPE HTML Public "-//W3C//DTD XHTML 1.0 transitional//en" "http://www.w3.org/TR/xhtml1/DTD/ Xhtml1-transitional.dtd "><HTMLxmlns= "http://www.w3.org/1999/xhtml"><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8" /><title>Untitled Document</title> <Scriptsrc= "Js/jquery-1.8.1.min.js"type= "Text/javascript"></Script> <styletype= "Text/css"> *{margin:0px;padding:0px;}. Main-1{Height:200px;background:#060;}. Box1{Height:200px;width:300px;background:#f00;float: Left;}. Box2{Height:200px;width:200px;background:#00f;float: Left;}. Main-2{Height:400px;width:800px;background:#000;   }. Box3{Height:200px;width:600px;background:#603;Margin-top:20px;  } </style></Head><Body>    <Divclass= "Main">   <Divclass= "Main-1">     <Divclass= "Box1"></Div>     <Divclass= "Box2"></Div>     </Div>          <Divclass= "Main-2">     <Divclass= "Box3"></Div>     </Div>   </Div></Body> </HTML> 

Demo

Pay attention to the margin-top in Box3

Workaround :
1, modify the height of the parent element, add padding-top style simulation (padding-top:1px; common)
2. Add Overflow:hidden for parent element; style (perfect)
3. Declare floats for parent or child elements (float:left; available)
4. Add border for parent element (border:1px solid transparent available)
5. Absolute positioning for parent element or child element declaration

Margin-top problem between parent element and child element (CSS hack)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.