YogeshChauhan.com

How to center an image horizontally and vertically?

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 */
}
dreamhost

Most Read

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

Recently Posted

Apr 7 Solution for “Yarn build: Failed because of a stylelint error” Apr 7 Make sure your links have descriptive text Apr 7 How to add Laravel to WordPress using Sage theme (and install Tailwind CSS)? Apr 2 How to create a sidebar using pure CSS? Apr 1 How to switch dark and light themes using pure CSS? Apr 1 How to calculate elapsed time in JavaScript?

You might also like these

How to Create a Copy of a Table in SQL and MySQL?SQL/MySQLHow to use GROUPING SETS to boost GROUP BY queries in Postgres?PostgresCommon Table Expressions (CTE) in PostgreSQLPostgresHow to implement NSNumberFormatter in Swift for currency?SwiftHow to get start index and end index (as int) of substring in Swift?Swiftsubstring() Method in JavaScriptJavaScriptWhat are Conditional Tags in WordPress?WordPressMicroservices vs Monolithic ArchitectureMiscOpen Source Security Tools for Defense SecurityMiscHow to add AppRoutingModule in Angular application using command line?AngularThe 8 Golden Rules of Programming I Have Learned in My CareerMiscWhat are Null Sessions?Misc