PROWAREtech

articles » current » css » center-elements-on-page

CSS: Center Elements on Page

How to center elements both vertically and horizontally on the page.

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

One way is to use display: table.

<!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 {
			display: table;
			position: absolute;
			width: 100%;
			height: 100%;
		}
			.center div {
				display: table-cell;
				vertical-align: middle;
				text-align: center;
			}
	</style>
</head>
<body>
	<div class="center">
		<div>content</div>
	</div>
</body>
</html>

Another 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>
		.center > div {
			position: absolute;
			top: 0;
			left: 0;
			bottom: 0;
			right: 0;
			display: flex;
			flex-wrap: wrap;
			justify-content: center; /* or space-around */
			align-items: center;
		}
	</style>
</head>
<body>
	<div class="center">
		<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>
		.center {
			position: fixed;
			top: 50%;
			left: 50%;
			-webkit-transform: translate(-50%, -50%);
			transform: translate(-50%, -50%);
		}
	</style>
</head>
<body>
	<div class="center">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. It has good compatibility including with IE6 (a difficult browser to program for).

<!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;
			text-align: center;
			line-height: 100px;
			background-color: red;
			color: white;
			font-weight: bold;
		}
	</style>
</head>
<body>
	<div class="center">content</div>
</body>
</html>

Coding Video

https://youtu.be/_LxORvUIU9s


PROWAREtech

Hello there! How can I help you today?
Ask any question

PROWAREtech

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
ACCEPT REJECT