How to align a logo image to center of navigation bar using HTML and CSS ?
Problem statement: You must have seen that while applying margin:auto property to the image tag in the navigation bar, the logo image in the navigation bar does not get centered.
Approach: As the image tag in CSS is an inline element, so the image tag will occupy only that much space which is required by it. So, in order to resolve this problem, we have assigned the display property of the image tag to “block” and then assign proper width and height to it. Assign the margin to “auto”. You will see that the logo image is now centered in the navigation bar.
HTML code: Following demonstrates the code for the above approach.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <style> #navbar { width: 100vw; height: 40px; border: 3px solid white; border-radius: 15px; background-color: green; } #navbar img { display: block; width: 40px; height: 40px; margin: auto; } </style></head> <body> <nav id="navbar"> <img src="5.jpeg" alt="Logo image"> </nav></body> </html> |
Output:



