How to Prevent Spacing Before and After DIV Tags

Using the DIV Tag Effectively

The element is a block-level element. Among other things, this means that most browsers will display DIV elements with a carriage return before and after the element, similar to a element. However, if you don't want your DIV elements to display this way, it's easy to fix with CSS:

div {
 display: inline; 

The CSS style display: inline; tells the browser to treat the normally block-level DIV element as an inline element similar to the element.

If You Want Your DIV to Remain a Block-Level Element

Changing a DIV to a block-level element may not be exactly what you want (honestly, it probably is not - doing so will open up a number of other layout challenges). Block-level elements can be easily floated in a layout and are treated as blocks within the page that typically contain other HTML content.

If all you want to do is remove the spacing around the DIV element, but you want it to remain a block-level element, you can do that with CSS as well:

div {
margin: 0;

The margin: 0; tells the browser to display the element without any spacing around it. This is part of the box model. The benefit of using the margin style is that your DIV element will still be a block-level element.

Before You Switch Your DIV Tags

But, before you switch all your DIV tags to be inline, make sure you need them to be inline. There are other tags that are already inline that might serve the purpose you are striving for with your DIV element without needing to make it inline simply for styling purposes.

If all you need to do is to wrap an element or area with an element to be styles, and it needs to be an inline element, the best tag to use would be the SPAN tag. It has many of the same properties as the DIV tag, but it's an inline element rather than a block element.