1

can anyone explain why putting margins in each tag still leaves a space inbetween the article and header tag but when I use the * selector the space gets removed. I don't necessarily want all elements with a margin of zero. I would rather set each one I want to 0.

snippet 1 below leaves a space in between header and article tag

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;
}

when I add this snippet below all spaces in between the article and header tag get removed, which is what I want, but I don't necessarily want 0 margin for all elements

*{ 
    margin: 0
}

Here is the 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>
chuckd
  • 13,460
  • 29
  • 152
  • 331

4 Answers4

2

There are default margins on the h1 and h2 elements which are not affected by your CSS until you apply the * reset rule.

If it does not compromise your layout, it should be sufficient to apply zero margins to h1, h2 as well. You can of course limit it using #header h1, #article h2 or something similar just in case.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
1

If you want to set the margin for a bunch of elements, but not all of them, there are a couple of options. Here are two of them:

/* 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;
}

I would also like to note that you don't need to have an id for your header element. Just use the header selector in your CSS.

0

An Asterisk (*) is the universal selector for CSS. Since this is a Universal Selector so every element used in document will have a margin:0.

Also it is not a good practice to use universal selector in this way.

*{ margin: 0;}
Kheema Pandey
  • 9,977
  • 4
  • 25
  • 26
  • Reading the question it's probably safe to assume the OP is aware of all this and doesn't actually intend to use `*` this way. – BoltClock Jun 03 '14 at 04:54
-3
body > * {
  margin: 0;
}
div,*{
    margin:0;
    position:relative;
}
Kisspa
  • 584
  • 4
  • 11
  • 2
    What is this supposed to be? Are you trying to answer the question, or are you making a suggestion, or are you trying to edit the code yourself, or...? – BoltClock Jun 03 '14 at 04:55