Joel 0

How can I place the header text in the middle of the div in the attached example?

4 answers

1
point

One way to centre vertically is this:

.header {
    background:#F00;
    padding:35px 0;
}

Note that I have removed the height. For a single-line heading the resulting height will be approximately 100px (assuming h1 text comes out at about 30px). The advantage is that if the text wraps to two lines for some reason, the heading expands to cope with it.

If you want 100px high (e.g. because the heading will actually have an image as a background) no matter what, try this:

.header {
    background:#F00;
    height:99px;
    border-top:1px solid #f00;

}
.header h1 {margin-top: 35px;
                  font-size:30px;}

The border on header is to stop what is called margin-collapsing on the h1.

Answered over 7 years ago by Richard Grevers
1
point

If you want to center it in both axis I recommend using either absolute positioning:

.header {position: relative;}

h1 {
       position: absolute;
       top: 50%;
       left: 50%;
       margin-top: -50px; /* formula: height of the H1 / 2, to check dimensions, use Web Developer Toolbar or Firebug */
       margin-left: -50px; /* formula: width of the H1 / 2, to check dimensions, use Web Developer Toolbar or Firebug */
       text-align: center;
    }

Or line height:

h1 {
   text-align: center;
   line-height: 300px;  /* the height of the canvas (in this case the .header), only works if you know it  */
}
Answered over 7 years ago by Jens Hedqvist
0
points

try

h1 {text-align:center;}
Answered over 7 years ago by Richard Grevers
Joel 0
0
points

its centered, but its still not in the middle

Answered over 7 years ago by Joel
  • Do you mean vertically rather than horizontally then? Richard Grevers over 7 years ago