41

I thought using float: right; would fix this, but it makes the button appear outside of the div. How do I solve this?

HTML

<div id="main">
  <h1>Title</h1> <button>Button</button>
</div>

CSS

#main {
  width: 200px;
  border: 1px dotted black;
}
h1 {
  margin: 0;
}
button {
  float: right;
}

JSFiddle

Joe
  • 461
  • 1
  • 4
  • 5

3 Answers3

62

The original answer suggested using inline-block and float to position the elements, but things have moved on since then. A more flexible solution today would be to use flex.

#main {
  border: 1px dotted black;
  display: flex;
  align-items: center; /* Vertical align the elements to the center */
}

h1 {
  margin: 0;
}

button {
  margin-left: auto; /* Push this element to the right */
}
<div id="main">
  <h1>Title</h1> <button>Button</button>
</div>

Old answer

Give your h1 display: inline-block to allow your elements to occupy the same row...

#main {
  width: 200px;
  border: 1px dotted black;
}
h1 {
  margin: 0;
    display: inline-block;
}
button {
  float: right;
}
<div id="main">
  <h1>Title</h1> <button>Button</button>
</div>
Turnip
  • 35,836
  • 15
  • 89
  • 111
  • 1
    In my case I wanted the heading text centered, so I was able to get that by replacing "display: inline-block" with "text-align: center". – Keith Bennett Aug 06 '20 at 22:07
16

Try like this:

#main {
  width: 200px;
  border: 1px dotted black;
}
h1 {
  margin: 0;
}
button {
  float: right;
}
<div id="main">
  <h1> Title <button>Button</button></h1> 
</div>

JSFIDDLE DEMO

or you can use the display:inline so they appear side-by-side.

Deepak Mahakale
  • 22,834
  • 10
  • 68
  • 88
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

Another great option is the flexbox use like this:

#main {
  width: 200px;
  border: 1px dotted black;
  display:flex;
}
h1 {
  margin: 0;
}

You can optionally add justify-content:space-between like this

#main {
  width: 200px;
  border: 1px dotted black;
  display:flex;
  justify-content:space-between
}
h1 {
  margin: 0;
}

or choose any other flexbox property

Here is a comprehensive guide of Flexbox

TysTysTys
  • 91
  • 4