1

Here is the code:

<header>
    <h1>Title</h1>
    <h2>Subtitle</h2>
</header>

Is there a way to align h1 to the left and h2 to the right with only using inlines, no floats, no absolute positioning? I have tried:

header {
    width: 100%;
}

header h1 {
    display: inline-block;
    text-align:left;    
}

header h2 {
    display: inline-block;
    text-align: right;    
}

got no luck: http://codepen.io/Gasimzada/pen/qFolb

Gasim
  • 7,615
  • 14
  • 64
  • 131
  • Curious, why the restriction on floats etc.? – j08691 Feb 13 '14 at 18:21
  • 2
    Possible duplicate of [Align two inline-blocks left and right on same line](http://stackoverflow.com/questions/10272605/align-two-inline-blocks-left-and-right-on-same-line) – sergdenisov Oct 10 '15 at 20:43

2 Answers2

2

Give em some width dimensions! Without, inline-block elements will default to the exact width of the contents.

header {
    width: 100%;
}

header h1 {
    display: inline-block;
    width: 49%; /* 50% might be suitable; codepen bumped to next line at 50-50 */
    text-align:left;    
}

header h2 {
    display: inline-block;
    width: 50%;
    text-align: right;    
}

http://codepen.io/anon/pen/tBfHm

Patrick Moore
  • 13,251
  • 5
  • 38
  • 63
  • 1
    it got bumped to the next line because you have white space between the 2 inline-block elements – Huangism Feb 13 '14 at 18:35
  • Yes the fact that the 2 headers are not connected in the markup creates a white-space. This is a very common when using inline-block – Huangism Feb 13 '14 at 18:40
  • 1
    The trick here is to set `header { font-size:0 }`, and then specify your `font-size`s in the `h1`& `h2`. No more issues with whitespace! – Rémi Breton Feb 13 '14 at 18:59
0

you can as well either use text-align:justify, display:table or display:flex; http://codepen.io/anon/pen/IwbBs

* {
  margin: 0px;
  padding: 0px;
  font-size: 100%;
  font-weight: inherit;
  font-family: inherit;
}

body {
    font-weight: 300;
    font-family: 'Open Sans', sans-serif;
    color: white;
}

header {
  width: 100%;
  padding: 10px;
  background: black;
}
header h1 {
  display: inline-block;
  text-align:left;
}

header h2 {
  display: inline-block;  
  text-align:right;
}
/* justify */
  .justify {
  text-align:justify;
    line-height:0px;
}
.justify * {
  line-height:1.2em;
}
.justify:after {
  content:'';
  width:99%;/* add an extra line to trigger justify on .. first-line */
  display:inline-block;
  vertical-align:top;
}
/* flex */
.flex {
  display:flex;
  justify-content:space-between;
}
/* table */
.table {
  display:table;
}
.table h1, .table h2 {
  display:table-cell;
}

... Float has already been told :)

G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129