Sean B. Durkin
Sean B. Durkin

Reputation: 12729

How to float to the right of, and level with block-level elements

I want a web page that looks like this ...

header {
  border-style: solid;
  border-top-width: 5px;
  background-color: red;
}

p {
  background-color: yellow;
}

header #btnLogIn {
  float: right;
  position: absolute;
  right: 170px;
  top: 40px;
}

header #btnGoogleLogIn {
  float: right;
  position: absolute;
  right: 30px;
  top: 40px;
}
<header>
  <h1>Site Title</h1>
  <button id="btnLogIn" type="button">Log in</button>
  <button id="btnGoogleLogIn" type="button">Log in with Google</button>
</header>
<hr/>
<p>Some text</p>

The buttons need to be on the same horizontal level as the h1 header, floating to the right, with some nice margin in between. The button captions can change dynamically (via language selection), so any solution with hard-coded right property values is a fail.

How can I get the buttons to float to the right, on the same row as the h1 element, in a way that is independent of button width? The solution needs to be css.

Upvotes: 0

Views: 51

Answers (3)

Mers
Mers

Reputation: 734

Would this work for you?

header {
  border-style: solid;
  border-top-width: 5px;
  background-color: red;
  display: flex;
  align-items: center;
}
header h1 {
  flex: 1;
}

header button {
  margin: 0 1em;
}
p {
  background-color: yellow;
}
<header>
  <h1>Site Title</h1>
  <button id="btnLogIn" type="button">Log in</button>
  <button id="btnGoogleLogIn" type="button">Log in with Google</button>
</header>
<hr/>
<p>Some text</p>

Upvotes: 1

sarneeh
sarneeh

Reputation: 1388

Flexbox is the answer:

HTML:

<header>
  <div class="header-left">
    <h1>Site Title</h1>
  </div>
  <div class="header-right">
    <button class="btn" type="button">Log in</button>
    <button class="btn" type="button">Log in with Google</button>
  </div>
</header>
<hr/>
<p>Some text</p>

CSS:

header {
  border-style: solid;
  border-top-width: 5px;
  background-color: red;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

header .btn {
  margin: 0 10px;
}

p {
  background-color: yellow;
}

Upvotes: 1

Temani Afif
Temani Afif

Reputation: 273021

Use flexbox like this:

header {
  border-style: solid;
  border-top-width: 5px;
  background-color: red;
  display: flex;
  align-items: center;
}

p {
  background-color: yellow;
}

header button {
  margin: 0 10px;
}

header h1 {
  margin-right: auto;
}
<header>
  <h1>Site Title</h1>
  <button id="btnLogIn" type="button">Log in</button>
  <button id="btnGoogleLogIn" type="button">Log in with Google</button>
</header>
<hr>
<p>Some text</p>

Upvotes: 1

Related Questions