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

Summary of methods to solve css margin overlap

巴扎黑
巴扎黑Original
2017-09-07 09:12:361527browse

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>

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;
}

(2) Add padding to the parent element


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

(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>

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


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

(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;
}

(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!

Statement:
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