Overlapping Margins in Div Elements
Question:
Why are the margins of the div elements in my code overlapping, causing the elements to bunch up?
Code:
<code class="css">.alignright {float: right} #header .social {margin-top: 50px;} #header .social a {display: inline-block;} #header .social .fb {width: 64px; height: 1px; padding-top: 60px; overflow: hidden;} #header .social .twit {width: 64px; height: 1px; padding-top: 60px; overflow: hidden;} #header .contact {margin: 20px 70px 20px 0; font-size: 14px; font-weight: bold;} #header .contact span {color: #FFFFFF;} #header .search {margin: 10px 0 0;}</code>
<code class="html"><div class="alignright"> <div class="social"> <a href="#" class="twit"></a> <a href="#" class="fb"></a> </div><!-- social --> <div class="contact"> Get in Touch: <span>+44 10012 12345</span> </div><!-- contact --> <div class="search"> <form method="post" action=""> <input type="text" value="" name="s" gtbfieldid="28"> </form> </div><!-- search --> </div></code>
Answer:
The overlapping margins are likely due to a phenomenon known as "margin collapse." This occurs when the bottom margin of one element and the top margin of an adjacent element combine to form a single, larger margin.
In your code, the bottom margin of the .social div and the top margin of the .contact div are collapsing, causing the elements to appear too close together.
According to the W3C, two margins collapse if they meet the following criteria:
Since the margins in your code meet these criteria, they will collapse.
Solution:
There are a few ways to solve this problem:
The above is the detailed content of Why are My Div Element Margins Overlapping and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!