Question3r
Question3r

Reputation: 3742

create a navbar with left and right aligned items

I want to create a navbar with some links on the left and a button on the right

#navbar {
  padding: 20px;
  border: 1px solid #000000;
}

#btn {
  padding: 6px 16px;
  float: right;
}
<div id="navbar">
  <a>link 1</a>
  <a>link 2</a>
  <button id="btn">button 1</button>
</div>

As you can see the button is not centered vertically. I tried to fix it using this code

#navbar {
  overflow: hidden;
  padding: 20px;
  border: 1px solid #000000;
}

.navbarElement {
  padding: 6px 16px;
}

#navbar a {
  float: left;
}

#buttonBar {
  float: right;
}
<div id="navbar">
  <a class="navbarElement">link 1</a>
  <a class="navbarElement">link 2</a>
  <div id="buttonBar">
    <button class="navbarElement">button 1</button>
  </div>
</div>

I think this solution is bad because I have to set a padding for the links too. I also think that there might be smarter solutions instead of using float?

I don't want to add many DOM elements to achieve the desired behaviour if possible.

Upvotes: 0

Views: 72

Answers (2)

Kosh
Kosh

Reputation: 18378

Just add a negative margin-top to your button:

#navbar {
  padding: 20px;
  border: 1px solid;
}

#btn {
  padding: 6px 16px;
  float: right;
  margin-top: -6px;
}
<div id="navbar">
  <a>link 1</a>
  <a>link 2</a>
  <button id="btn">button 1</button>
</div>

Upvotes: 1

doğukan
doğukan

Reputation: 27381

it could help.

#navbar {
  overflow: hidden;
  padding: 20px;
  border: 1px solid #000000;
  display:flex;
}

.links {
  display:flex;
  justify-content:flex-start;
  align-items:center;
  flex:1;
}

.links a {
  padding:0 10px;
}

#buttonBar {
  flex:1;
  display:flex;
  justify-content:flex-end;
  align-items:center;
}
<div id="navbar">
  <div class="links">
    <a class="navbarElement">link 1</a>
    <a class="navbarElement">link 2</a>
  </div>
  <div id="buttonBar">
    <button class="navbarElement">button 1</button>
  </div>
</div>

Upvotes: 4

Related Questions