This article mainly introduces the detailed CSS margin overlap of several solutions, small series feel very good, now share to everyone, also for everyone to do a reference. Let's take a look at it with a little knitting.
Today we've sorted out some ways to prevent margins from overlapping with CSS
First assume a set of DOM structures
<p class= "Parent" > <p class= "Child" > </p></p>
Typically, if you set a margin on a child element, this property produces the same effect for the parent element, but
This is not really the result we want, we just want to set the margin for the child element, so what should we do now?
(1) Set the border for the parent element
. parent { width:300px; height:300px; border:1px solid #ccc;}. Child { width:200px; height:200px; margin:20px;}
(2) Adding 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 a wide height above the child element and remember that it has a wide height.
<p class= "Parent" > <p style= "width:20px;height:20px;margin-top:" ></p> <p class= " Child "> </p></p>
(4) Set the Overflow:hidden for the parent element; Property
. parent { Overflow:hidden; width:300px; height:300px;}. Child { width:200px; height:200px; margin:20px;}
(5) Set Display:inline-block for child elements (such as if the fruit element is an inline element or the inline block level element does not cause margin overlap)
. parent { width:300px; height:300px;} . Child { width:200px; height:200px; margin:20px; Display:inline-block;}
(6) To leave the child elements out of the document flow this implementation of the method has a lot of, floating, absolute positioning, etc., here I do not do a specific explanation.