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.
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>
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.