Search code examples
htmlcssalignmentz-index

How to align logo to div boundaries while having another element in the same div?


I am designing a navbar with my school logo in between and an account picture in the right. I want the logo to ignore the account picture div and align to the div. View pictures for more context.

|--------logo--------|
|-------logo-------ac|

I cannot post a picture because of low reputation points so here is a textual representation

I want the logo to align just like in the first line but with the account picture.

I tried using z-index but it didn't work. :(


Solution

  • Well, if you want the logo to be always centre and the account picture is going to be always at the right most corner, you can do with positioning. Check this out below:

    header {
      overflow: hidden;
      text-align: center;
      position: relative;
      border: 1px solid #ccc;
      margin-bottom: 20px;
    }
    
    header h1 {
      margin: 0;
    }
    
    header h1 img {
      height: 100px;
    }
    
    header .acct {
      width: 50px;
      position: absolute;
      right: 0;
      top: 50%;
      right: 20px;
      margin-top: -25px;
    }
    <header>
      <h1>
        <a href=""><img src="https://i.imgur.com/iP7576O.png" alt="Logo" /></a>
      </h1>
      <img src="https://i.imgur.com/JcFpfoF.jpg" alt="Praveen" class="acct" />
    </header>
    
    <p>Here's a comparison for the logo alone centred.</p>
    
    <header>
      <h1>
        <a href=""><img src="https://i.imgur.com/iP7576O.png" alt="Logo" /></a>
      </h1>
    </header>

    With the above code, you will be able to achieve what you want. Check out the preview.

    preview

    The border can be removed and it's shown only for an illustrative purpose.