0

My objective

I'm trying to do a navigation bar in CSS with two buttons on the left side and one image on the right. The problem is that my image has to fit the size of the navigation bar, and at the same time, it has to be vertically centered. If anyone could help me solve this, I would be truly glad.

Solution: I ended up solving it by using "flex" and "margin" (the navigation bar display property was set to flex and the icon margin-left was set to auto, making it go to the right of the flex row). Here is a code example: https://jsfiddle.net/572bag0z/#&togetherjs=QJn2LqjxTQ

.top-nav {
    position: fixed;
    display: flex;
    overflow: hidden;
    background-color: white;
    align-items: center;
    height: 4em;
    width: 100%;
    box-shadow: 0 .5px 4px;
}
.top-nav a {
    float: left;
    color: #f2f2f2;
    text-align: center;
    text-decoration: none;
    color: black;
    text-transform: uppercase;
    font-weight: 600;
    padding: 2em;
}
.top-nav img {
    width: 3em;
    margin-left: auto;
    margin-right: .75em;
}
  • Can you post what you have tried? Please read: https://stackoverflow.com/help/minimal-reproducible-example – Wex Sep 02 '20 at 17:49
  • Post a code example. I use http://jsfiddle.net – desbest Sep 02 '20 at 18:08
  • I ended up solving it by using "flex" and "margin" (setting the margin-left of the icon to auto). Here is a code example of what I did https://jsfiddle.net/572bag0z/#&togetherjs=QJn2LqjxTQ – briones-gabriel Sep 03 '20 at 23:08

2 Answers2

1

Generally and historically, centering elements along the vertical axis has been a pain. Things have gotten much better though, and now there are some pretty easy ways to about it. I'd recommend looking into using flexbox's align-items property.

drewiepooey
  • 164
  • 5
  • Thank you very much. As you say, the vertical axis has always been a pain and flexbox has come to solve our suffering. Again, thank you bro! – briones-gabriel Sep 02 '20 at 18:19
0

I think the easiest way of doing this is adding margin-top:auto; margin-botom:auto; to the img and display:flex; or display: grid; to the container. It wouldn't work without flex or grid. Codepen: https://codepen.io/thescv/pen/YzqrLeK

NemoRu
  • 1
  • 2