Margin-Top push outer div down

2018-12-31 13:11发布

I have a header div as the first element in my wrapper div, but when I add a top margin to a h1 inside the header div it pushes the entire header div down. I realize this happens whenever I apply a top margin to the first visible element on a page.

Here is a sample code snippet. Thanks!

div#header{
	width: 100%;
	background-color: #eee;
	position: relative;
}

div#header h1{
	text-align: center;
	width: 375px;
	height: 50px;
	margin: 50px auto;
	font-size: 220%;
	background: url('../../images/name_logo.png') no-repeat;
}
<div id="header">
	<h1>Title</h1>
	<ul id="navbar"></ul>
</div>

标签: html css xhtml
7条回答
浪荡孟婆
2楼-- · 2018-12-31 14:05

This are some of the ways to avoid margin collapsing between parent-child elements. Use the one that fits better with the rest of your styling:

  • Set display to other than block.
  • Set float to other than none.
  • Remove the margin, and use instead padding. For example if you had margin-top: 10px, replace with padding-top: 10px;.
  • Remove the margin, and use instead position (absolute or relative) with attributes top, bottom, etc. For example if you had margin-top: 10px, replace with position: relative; top: 10px;.
  • Add a padding or a border in the side where the margins are collapsing, to the parent element. The border can be 1px and transparent.
  • Set overflow to other than visible to the parent element.
查看更多
登录 后发表回答