Centering an image in a div

Is this a proper way to center a image in a div? Codepen Correctly coded I mean…

<div id="image_wrap">
<div id="image">
<img src="https://m1.behance.net/rendition/modules/133243137/disp/8ccbc07686bdc862ad4a1ee01d81676d.png">
  </div>
  </div>

#image_wrap{
  background-color:gray;
  width:984px;
  margin:auto;
}

#image{
  margin:auto;
  width:60%;
  
}
#image img{
Width:100%;
Height:auto;
}

Or height 100 width auto will scale the image to the container…

As for centering , if you make #image_wrap display flex… You can align content centre and vertical align… Difficult to do now cause on phone but Google flex align

No need for the extra div.

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
#image_wrap {
	background-color:gray;
	width:984px;
	margin:auto;
}
#image_wrap img {
	margin:auto;
	width:60%;
	height:auto;
	display:block;
}
</style>
</head>

<body>
<div id="image_wrap">
		<img src="https://m1.behance.net/rendition/modules/133243137/disp/8ccbc07686bdc862ad4a1ee01d81676d.png">
</div>
</body>
</html>

The image was set to display:block and then margin:auto works to center it. You could leave the image as inline and set text-align:center on the parent.

e.g.

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
#image_wrap {
	background-color:gray;
	width:984px;
	margin:auto;
	text-align:center;
}
#image_wrap img {
	width:60%;
	height:auto;
}
</style>
</head>

<body>
<div id="image_wrap">
		<img src="https://m1.behance.net/rendition/modules/133243137/disp/8ccbc07686bdc862ad4a1ee01d81676d.png">
</div>
</body>
</html>

That’s the basic ways unless you want vertical alignment also as mentioned by proc3ss above.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.