Scotts Web Dev Banner
Did you notice... every article on this site has an associated video? Consider subscribing to Scotts Web Dev on YouTube! :)

How To Center An Element Horizontally & Vertically In A Container

There are at least 3 ways to center an element within a container

Method #1:
Use a flexbox on the container with:

.container {
  display: flex;
  align-items: center;
  justify-content: center;
}

Method #2:
Use a grid on the container with:

.container {
  display: grid;
  place-items: center;
}

Method #3:
Absolutely position the child element with:

.container {
  position: relative;
}
.element {
  position: absolute;
  top: 50%;
  left: 50%;transform: translate(-50%, -50%);
}

Full Demo Page

Here’s a full demo page for you to play around with.

<html>
	<head>
		<title>ScottsWeb.Dev - Center Element In Container</title>
	</head>
	<style>
		.container {
			width: 50%;
			height: auto;
			aspect-ratio: 1.5/1;
			margin: 0 auto;
			position: relative;
			border: solid 1px black;
			position: relative;
		}
		.element {
			width: 200px;
			height: 150px;
			background-color: lightgreen;
			border: solid 1px black;
			display: block;
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
		}
	</style>
	<body>
		<div class="container">
			<div class="element"></div>
		</div>
	</body>
</html>

Related Articles