Horizontal Centering
CSS offers several ways of centering things horizontally, and the type of element decides which one fits.
Center Align Block Elements
A block-level element like a <div> is centered with margin: auto, provided it has a width. Without one, the element stretches to fill its container.
Note: When width is missing or set to 100%, center aligning does nothing on block-level elements.
Example
Here a <div> element with a width of 50% sits in the center.
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Center Block Element</title>
<style>
.center {
margin: auto;
width: 50%;
border: 3px solid green;
padding: 10px;
}
</style>
</head>
<body>
<h2>Center Align a Block Element</h2>
<div class="center">
<p>This div element is centered.</p>
</div>
</body>
</html>
Center Align Text
Text inside a block-level element is centered with text-align: center.
Example
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Center Text</title>
<style>
p {
text-align: center;
}
</style>
</head>
<body>
<h2>Center Align Text</h2>
<p>This text is centered.</p>
</body>
</html>
Center Align an Image
An image needs two steps to be centered: turn it into a block element with display: block, then set both margin-left and margin-right to auto.
Example
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Center Image</title>
<style>
img {
display: block;
margin-left: auto;
margin-right: auto;
width: 40%;
}
</style>
</head>
<body>
<h2>Center an Image</h2>
<img src="madrid.jpg" alt="Madrid">
</body>
</html>
Left and Right Align - Using position
Setting position: absolute is one way to align elements to the left or right.
Note: Elements positioned this way leave the normal flow and may overlap other elements.
Example
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Right Align with Position</title>
<style>
.right {
position: absolute;
right: 0px;
width: 300px;
border: 3px solid green;
padding: 10px;
}
</style>
</head>
<body>
<h2>Right Align with position</h2>
<div class="right">
<p>This div element is positioned to the right, with the position: absolute property.</p>
</div>
</body>
</html>
Left and Right Align - Using float
The float property offers a different way to align an element to the left or right.
Example
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Right Align with Float</title>
<style>
.right {
float: right;
width: 300px;
border: 3px solid green;
padding: 10px;
}
</style>
</head>
<body>
<h2>Right Align with float</h2>
<div class="right">
<p>This div element has float: right.</p>
</div>
</body>
</html>