我有一个div作为我页面中的第一个元素。但是,大约20 px的空白区域将它与页面顶部分开。
我已将<body>
和<html>
标记的填充和边距设置为零,如下所示:
html, body {
padding: 0px;
margin: 0px;
}
然而,空白继续显示:
在浏览器开发工具中检查文档显示:
<html>
元素占用包括空白作为一个补丁修复,我将此规则添加到css中以删除空白:
html {
margin-top: -21.437px;
}
但对我而言,这似乎是糟糕的代码。 是否有更正确/更优雅的方法来解决这个问题,或者我有什么东西可以忽略?
完整代码:
html, body {
padding: 0px;
margin: 0px;
}
body { /* Note removing this rule does not fix the problem */
margin: auto;
}
.header-background {
background-color: #FFC107;
width: 100;
}
.content {
width: 1024px;
margin: 0 auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- The above 2 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<!-- CSS -->
<link href="css/main.css" rel="stylesheet">
<!-- JavaScript -->
<script src="js/jquery/jquery-2.1.4.min.js" defer></script>
</head>
<body>
<div class="header-background">
<div class="content">
<h1>Header text</h1>
<p>Supporting text</p>
<a href="about.html" role="button">Learn more »</a>
</div>
</div>
</body>
</html>
答案 0 :(得分:3)
而不是html, body
使用*
将解决问题。它将删除所有默认的margin
和padding
占用。
* {
padding: 0px;
margin: 0px;
}
body { /* Note removing this rule does not fix the problem */
margin: auto;
}
.header-background {
background-color: #FFC107;
width: 100;
}
.content {
width: 1024px;
margin: 0 auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- The above 2 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<!-- CSS -->
<link href="css/main.css" rel="stylesheet">
<!-- JavaScript -->
<script src="js/jquery/jquery-2.1.4.min.js" defer></script>
</head>
<body>
<div class="header-background">
<div class="content">
<h1>Header text</h1>
<p>Supporting text</p>
<a href="about.html" role="button">Learn more »</a>
</div>
</div>
</body>
</html>
答案 1 :(得分:3)
您的 .content h1 正在使用默认边距,因此请将其替换为0px:
html, body {
padding: 0px;
margin: 0px;
}
body { /* Note removing this rule does not fix the problem */
margin: auto;
}
.header-background {
background-color: #FFC107;
width: 100;
}
.content {
width: 1024px;
margin: 0 auto;
}
.content h1 {
margin:0px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- The above 2 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<!-- CSS -->
<link href="css/main.css" rel="stylesheet">
<!-- JavaScript -->
<script src="js/jquery/jquery-2.1.4.min.js" defer></script>
</head>
<body>
<div class="header-background">
<div class="content">
<h1>Header text</h1>
<p>Supporting text</p>
<a href="about.html" role="button">Learn more »</a>
</div>
</div>
</body>
</html>