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 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #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

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Can we execute conditions in SQL?SQL/MySQLJavaScript Number MethodsJavaScriptHow to show slider value in HTML5 range input using JavaScript?HTMLHow to redirect or load a new document using JavaScript?JavaScriptfirst-of-type and last-of-type selectors in CSSCSSReverse a String in JavaScriptJavaScriptWhat is a component helper function in React?ReactHow to change CSS with jQuery?CSSWhat Is a Graph Database?MiscellaneousHow to obfuscate JavaScript code to hide it from View Source?JavaScript3 Ways we can create URLSearchParams Objects in JavaScriptJavaScriptKilling A Project Part 2: Who should make the decision to kill a project?Miscellaneous