任何人都可以解释为什么在每个标记中放置边距仍会在文章和标题标记之间留下空格,但是当我使用*选择器时,空格会被删除。我不一定希望所有元素的边距为零。我宁愿将我想要的每一个设置为0。
下面的代码段1在标题和文章标记之间留下了空格
body
{
background-color: yellow;
margin: 0 0 0 0;
}
#header
{
background-color: blue ;
margin: 0 0 0 0;
width: 100%;
height: 40px;
border: 3px solid black;
}
#article
{
background-color: red;
margin: 0 0 0 0;
}
#search {
background-color: #a6dbed;
height: 500px;
margin: 0 0 0 0;
}
#mostdesired
{
background-color: #c7d1d6;
height: 200px;
margin: 0 0 0 0;
}
当我在文章和标题标签之间的所有空格下方添加此片段时,这是我想要的,但我不一定要为所有元素保留0个边距
*{
margin: 0
}
这是html
<body>
<header id="header">@*<h1>Welcome</h1>*@</header>
<article id="article">
<section id="search"><h2>this is the search</h2>@RenderBody()</section>
<section id="mostdesired"><h2>This is the most section</h2></section>
</article>
</body>
答案 0 :(得分:2)
在您应用h1
重置规则之前,h2
和*
元素上的默认边距不受CSS影响。
如果它不会影响您的布局,那么对h1, h2
应用零边距也应该足够了。您当然可以使用#header h1, #article h2
或类似的东西限制它,以防万一。
答案 1 :(得分:1)
如果你想为一堆元素设置边距,而不是所有元素,有几个选项。以下是其中两个:
/* this gives all the desired elements the same margin */
#header, #article, #search, #mostdesired {
margin: 0;
}
/* this gives all direct children of the body the same margin */
body > * {
margin: 0;
}
我还要注意,您不需要为标头元素设置ID。只需在CSS中使用header
选择器。
答案 2 :(得分:0)
Asterisk(*)是CSS的通用选择器。由于这是一个通用选择器,因此文档中使用的每个元素都将具有margin:0
。
以这种方式使用通用选择器也不是一个好习惯。
*{ margin: 0;}
答案 3 :(得分:-3)
body > * {
margin: 0;
}
div,*{
margin:0;
position:relative;
}