PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, November 17, 2022

[FIXED] How to vertically center an <img> with CSS and NOT overlap a text?

 November 17, 2022     css, html, image, overlapping, vertical-alignment     No comments   

Issue

I'm trying to put a logo in my forum, but neither the engine nor the template I use support this. So I decided to give it a try and put it. It seems so simple, but it's not.

I've tried at least 5 ways I found in the net (mostly from StackOverflow), but they either do not work at all (image not centered vertically) or solve the problem only partially as the image overlaps a text following it.

The only solution which worked in terms of vertical-centering is based on position: absolute and margin: auto

<img src="/EL3232.png" width="32" height="32" style="
        float: left;
        position: absolute;
        top:0;
        bottom:0;
        margin:auto;
">

It has however a side effect: the image overlaps the forum title text.

The HTML is quite complex I would say and its simplification for the post is not easy (a lot of CSS for each preceding element), so I think I will just pass the link to my website, so you knew what I mean: http://www.forumextalife.pl/

It's basically a hierarchy like this: <div> -> <nav> -> <div> -> <div> -> <a>. I want to put an <img> containig the logo inside this <a> tag. To be exact - the element in the website is: <a class="navbar-brand">

I hope you guys can solve it. I've never thought this is gonna be so complicated to have simply an image centered vertically and not overlapping text.


Solution

The cleanest approach is probably to set the image as a background image of .navbar-brand, with a bit of padding and/or line height so that the title aligns appropriately alongside it. Something like this...

.navbar-brand {
   background:url(/EL3232.png) left center no-repeat;
   display:inline-block;
   padding-left:40px;
   height:32px;
   line-height:32px;
} 

Keep responsive design in mind, though - I see your title already is limited at mobile sizes.



Answered By - RichardB
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing