Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing body margin in CSS

I'm new to web development, and met a problem when removing margin of body.

There's space between the very top and "logo" There's space between the very top of the browser and "logo" text. And my code is here on jsbin.

Is body { margin: 0;} wrong if I'd like to remove the space?

like image 884
chenghuayang Avatar asked May 13 '15 07:05

chenghuayang


People also ask

What does margin 10px 5px 15px 20px mean?

margin: 10px 5px 15px 20px; top margin is 10px. right margin is 5px. bottom margin is 15px. left margin is 20px.

What is body margin in CSS?

The CSS margin properties are used to create space around elements, outside of any defined borders. With CSS, you have full control over the margins. There are properties for setting the margin for each side of an element (top, right, bottom, and left).

What does margin 0 Auto in CSS do?

So in margin: 0 auto, the top/bottom margin is 0, and the left/right margin is auto, Where auto means that the left and right margin are automatically set by the browser based on the container, to make element centered.

How do I remove the extra spacing from the edges of a Web page?

style-test-1. This spacing exists because of the default margin of the body element. Because of this, we can remove the spacing by setting the margin of the body element to 0. This is done in the style-test-2. html page.


2 Answers

I would say that using:

* {
  margin: 0;
  padding: 0;
}

is a bad way of solving this.

The reason for the h1 margin popping out of the parent is that the parent does not have a padding.

If you add a padding to the parent element of the h1, the margin will be inside the parent.

Resetting all paddings and margins to 0 can cause a lot of side effects. Then it's better to remove margin-top for this specific headline.

like image 51
andeersg Avatar answered Oct 12 '22 08:10

andeersg


Some HTML elements have predefined margins (namely: body, h1 to h6, p, fieldset, form, ul, ol, dl, dir, menu, blockquote and dd).

In your case it's the h1 causing your problem. It has { margin: .67em } by default. If you set it to 0 it will remove the space.

To solve problems like these generally, I recommend using your browser's dev tools. For most browsers: right-click on the element you want to know more about and select "Inspect Element". In the "Styles" tab, at the very bottom, you have a CSS box-model. This is a great tool for visualising borders, padding and margins and what elements are the root of your styling headaches.

like image 11
Björn Helgeson Avatar answered Oct 12 '22 08:10

Björn Helgeson