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 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #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
You might also like these
What is a Strict Requirement in PHP 7 Function Declarations?PHPHow to Commit and Rollback Changes in SQL?SQL/MySQLHow to create a flip pricing table using CSS and JavaScript?CSSHow to float an image around texts?CSSHow to set up the local environment and workspace for Angular development?AngularABS and NEG functions in Envision BasicEnvision BasicHow to create a Bootstrap style accordion using CSS and JavaScript?CSSWhat is a component helper function in React?ReactAdvanced nesting in Sass (SCSS) using at-rootSCSSHow to display and animate image on scroll using JavaScript?JavaScriptHow to add MySQL alternate port and sockets/pipes in WordPress?WordPressHow to clean up after a plugin uninstall in WordPress?WordPress