108

I am having a problem with removing linebreaks after the <h1> tag, as everytime it prints, it adds a line break straight after it, so something like <h1>Hello World!</h1> <h2>Hello Again World!</h2> prints out like this:

Hello World!

Hello Again World!

I am unsure on what tags I need to change in CSS, but I expect it's something to do with the padding or margins

I also want to keep the vertical padding if at all possible.

Ben Lee
  • 52,489
  • 13
  • 125
  • 145
Jack Wilsdon
  • 6,706
  • 11
  • 44
  • 87

4 Answers4

175

Sounds like you want to format them as inline. By default, h1 and h2 are block-level elements which span the entire width of the line. You can change them to inline with css like this:

h1, h2 {
    display: inline;
}

Here's an article that explains the difference between block and inline in more detail: http://www.webdesignfromscratch.com/html-css/css-block-and-inline/

To maintain vertical padding, use inline-block, like this:

h1, h2 {
    display: inline-block;
}
Ben Lee
  • 52,489
  • 13
  • 125
  • 145
15

<h1> tags have {display: block} set. They are block-level elements. To turn this off:

{display: inline}
tkone
  • 22,092
  • 5
  • 54
  • 78
  • by default h tags using margin, padding so we have to remove these – Adeel Mughal Feb 20 '12 at 12:34
  • I also want to keep the vertical padding if at all possible, I have tried display: inline;, but it no longer has it's vertical padding. – Jack Wilsdon Feb 20 '12 at 12:35
  • 1
    removing padding and margin does not remove the new line. the new line is caused because they are block-level elements, which mean they take up all the horizontal space where they appear (by default). Thus unless you do floats, change display or some other properties, you will ALWAYS have a newline after an `h*` tag. – tkone Feb 20 '12 at 12:39
  • @JackWilsdon Ben Lee has already updated to show how to maintain vertical-padding easily, so I won't bother with a me too after your edit. – tkone Feb 20 '12 at 12:41
4

I just solved this problem by setting h1 margin value to minus in html style section. It works perfecly for my needs.

<style>
h1 { 
    display: block;
    font-size: 0.9em;
    margin-top: -1.91em;
    margin-bottom: -1.91em;
    margin-left: 0;
    margin-right: 0;
    font-weight: bold;
}
</style>
<h1 style="text-align:center"> Headline </h1>
Jacek
  • 67
  • 1
  • 2
    This works for removing the vertical padding instead of the line break. – juil Apr 30 '16 at 17:17
  • I googled for the wrong thing while I noticed that this answer is actually what I was looking for. Great solution, although not the answer to the question. Thanks anyway! :) – Semmel Sep 27 '20 at 18:58
-7

<style>
h1 {
    padding: 0px;
    margin: 0px;
}
</style>
Floern
  • 33,559
  • 24
  • 104
  • 119