Dave Dave - 11 months ago 63
CSS Question

how to position subheader right under header

This may be a silly question, but what is the best way to position a subheader right under a main header? I have a main header (h1) and the css is below:

h1 {
color: #000;
position: relative;
position: absolute;
left: 50%;
top: 20%;
-webkit-transform: translateX(-50%);
transform: translateX(-50%);
white-space: nowrap;


I want to put a subheader directly underneath it, but am unsure how to position it without specifying top: "x" px;

Any suggestions?

Answer Source

There are no silly questions! we all started exactly where you are :) First off as Trevor has said you have 2 position properties assigned to this element when you can only assign one. Second I would not use absolute or relative positioning to accomplish what you want here since it is a bit heavy handed. Also using absolute positioning + translate 50% is not completely friendly to some browsers. The best solution in this case would be to wrap the heading and your sub heading inside of a parent div tag and assign that parent div tag the CSS property of text-align: center. The reason for this is your parent div will be a block level element and span the entire width of the container, then adding text-align: center will center all inline children elements within that parent. https://developer.mozilla.org/en-US/docs/Web/CSS/text-align

code pen: http://codepen.io/chasereckling/pen/gwJkgN

  <h2>SUB HEADING</h2>

    div {text-align: center;}

hope this helps!