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
How to insert Bootstrap 4 in Angular 9 app?AngularHow to create a Progress Bar using JavaScript?JavaScriptWhat are Conditional Tags in WordPress?WordPressHow to create ‘share on LinkedIn’ link using just HTML?HTMLperspective property in CSSCSSA list of wp-cli commands to use via SSHWordPressPHP Login System using PDO Part 1: Create User Registration PagePHPFile System Integrity: How to Keep an Eye on Your Files and Folder Change?MiscellaneousCreate dynamic selectors using SCSS (Sass)SCSSWhat Is a Graph Database?MiscellaneousHow to scroll contents of HTML body horizontally and vertically using JavaScript?JavaScriptHow to vertically and horizontally align text and image block (without flex or grid) in CSS?CSS