Html – Float a div in top right corner without overlapping sibling header

csshtml

Having a div and a h1 inside a section, how do i float the div in the top right corner without overlapping the text of the header ?

The HTML code is the following:

<section>
  <h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>
  <div><button>button</button></div>
</section>

Using this CSS code:

section { position: relative; }
h1  { display: inline; }
div {
    position: absolute;
    top: 0;
    right: 0;
}

Using this CSS code:

h1  { display: inline; }
div { float: right;    }

I know there is a lot of similar questions but I couldn't find one solving this case.

Best Answer

If you can change the order of the elements, floating will work.

section {
  position: relative;
  width: 50%;
  border: 1px solid;
}
h1 {
  display: inline;
}
div {
  float: right;
}
<section>
  <div>
    <button>button</button>
  </div>

  <h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>
</section>

​By placing the div before the h1 and floating it to the right, you get the desired effect.