Home > Web Front-end > CSS Tutorial > Summary of methods to solve css margin overlap

Summary of methods to solve css margin overlap

巴扎黑
Release: 2017-09-07 09:12:36
Original
1536 people have browsed it

This article mainly introduces several solutions to the detailed explanation of CSS margin overlap. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor to take a look.

Today I have sorted out several methods of using CSS to prevent margin overlap.

Let’s first assume a set of dom structures


<p class="parent">
    <p class="child">
    </p>
</p>
Copy after login

Normally, if you set margin for a child element, this attribute will have the same effect on the parent element. However,

This is actually not the result we want. We just We want to set margin on child elements, so what should we do now?

(1) Set a border to the parent element


.parent { 
    width: 300px;       
    height: 300px;
    border: 1px solid #ccc;
}
.child {
    width: 200px;
    height: 200px;
    margin: 20px;
}
Copy after login

(2) Add padding to the parent element


.parent {
    padding: 1px;
    width: 300px;
    height: 300px;
}
.child {
    width: 200px;
    height: 200px;
    margin: 20px;
}
Copy after login

(3) Add a sibling element with width and height above the child element. Remember that there is width and height.


<p class="parent">
     <p style="width: 20px;height: 20px;margin-top: "></p>
     <p class="child">
     </p>
</p>
Copy after login

(4) Set the overflow: hidden; attribute to the parent element


.parent {
    overflow: hidden;
    width: 300px;
    height: 300px;
}
.child {
    width: 200px;
    height: 200px;
    margin: 20px;
}
Copy after login

(5) Set display: inline-block for the child element; (If the child element is an inline element or an inline block-level element, there will be no margin overlap problem)


.parent {
    width: 300px;
    height: 300px;
} 
.child {
    width: 200px;
    height: 200px;
    margin: 20px; 
    display: inline-block;
}
Copy after login

(6) There are many ways to separate sub-elements from the document flow, such as floating, absolute positioning, etc. I will not give a detailed explanation here.

The above is the detailed content of Summary of methods to solve css margin overlap. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template