Yogesh Chauhan's Blog

How to center an image horizontally and vertically?

in CSS on September 26, 2020

We can use flex to center an image horizontally and vertically. But that is just one way to do it. There are multiple ways to do that.

Example 1

HTML


<div class="container">
 <img src="image_path" />
</div>

CSS


html, body, .container {
 height: 100%;
}

.container {
 display: flex;
 justify-content: center; /* horizontal center */
}

img {
 align-self: center; /* vertical center */
}

Example 2

HTML


<img src="image_path" />

CSS


html, body {
 height: 100%;
}

body {
 display: flex;
 justify-content: center; /* horizontal center */
 align-items: center; /* vertical center */
}

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface #Jan 14 How to display a student’s individual transcript in Colleague? #Jan 11 How to install PuTTY on a MacOS?
You might also like these
Variables and Distance Functions in SCSS (Sass)SCSSWhat’s a Web Storage API in JavaScript?JavaScriptThe basics of @import rule in SCSS (Sass)SCSSHow to avoid element shift on border change while hovering in CSS?CSSAND, OR and NOT boolean operators in Envision BasicEnvision BasicHow to Access a Global Variable From Inside a Function in PHP?PHPWhen you don’t want to @forward every member in SCSS (Sass)SCSSHow to include CSS and JavaScript files in your WordPress plugin?WordPressFew more :nth-child examples in CSSCSSrandom function in SCSS (Sass)SCSSA short basic guide on states in ReactReactWordPress: How to find all posts from a custom post type with specific custom field?WordPress