Center Elements on Screen with CSS

There are a few ways to center elements on the screen even if the width and height is not known.

One way to center when the width and height is not known. > is a child selector and selects all the children of the div with class "middle".

<!DOCTYPE html>
<html>
<head>
	<title>title here</title>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<style>
		.middle > div {
			position: absolute;
			top: 0;
			left: 0;
			bottom: 0;
			right: 0;
			display: flex;
			flex-wrap: wrap;
			justify-content: space-around;
			align-items: center;
		}
	</style>
</head>
<body>
	<div class="middle">
		<div>
			<div>content</div>
		</div>
	</div>
</body>
</html>

And yet another way to center when the width and height is not known.

<!DOCTYPE html>
<html>
<head>
	<title>title here</title>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<style>
		.middle {
			position: fixed;
			top: 50%;
			left: 50%;
			-webkit-transform: translate(-50%, -50%);
			transform: translate(-50%, -50%);
		}
	</style>
</head>
<body>
	<div class="middle">content</div>
</body>
</html>

Lastly, center when the width and height IS known. This is a less elegant solution than above but it may work well for things like images.

<!DOCTYPE html>
<html>
<head>
	<title>title here</title>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<style>
		.center {
			position: absolute;
			top: 50%;
			left: 50%;
			margin-top: -50px; /* subtract half the height */
			margin-left: -50px; /* subtract half the width */
			width: 100px;
			height: 100px;
		}
	</style>
</head>
<body>
	<div class="center">content</div>
</body>
</html>