The sub-element's margin-top will affect the parent element, and the margin-top will affect

Source: Internet
Author: User

The sub-element's margin-top will affect the parent element, and the margin-top will affect

--- Restore content start ---

When I was writing a project, I found that I wanted to add some margin between the parent and child elements, but the parent element produced the margin-top, So Baidu later found the cause.

In the css2.1 box model

In this specification, the expression collapsing margins means that adjoining margins (no non-empty content, padding or border areas or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin. all the adjacent two or more boxes of elements of the margin will be merged into a margin share. Adjacent Elements are defined as the same level or nested box elements, and they are separated by no non-empty content, Padding, or Border.

If the top margin of the child element of the parent element, margin-top, if it does not touch a valid border or padding, they will be shared before (the parent element will have margin-top ). Therefore, the above problems may occur. This also happens when the same level of Box elements meet the preceding conditions.

Solution:

1. Add a border-top or padding-top to the middle element in the parent element example to solve this problem.

2. Use floating or absolute positioning of sub-elements absolute

3. parent-level overflow: hidden (sharing means that both the parent and the child have the margin-top, but it is still in the upper part. overflow allows the child element to be hidden beyond the parent element, that is, mrgin-top, however, it is not recommended that the parent and child elements be separated)

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.