How to Horizontally Center Contents Within a Div
There are several ways that can be used to horizontally align the contents of the HTML <div> element to the center. To achieve your desired result, you need to use some CSS properties, which we’ll demonstrate in this snippet.
Solutions with CSS
You can use the CSS justify-content property, which will align the items when they do not use all the available space horizontally.
In the example below, we set the justify-content property to "center" and add the display property specified as "flex". We set the text-align property to “center” and specify the border, height, and padding of our <div>.
Example of horizontally centering the content of a <div> with the justify-content property:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
div {
border: 2px solid lightblue;
height: 100px;
padding: 10px 0;
display: flex;
justify-content: center;
}
</style>
</head>
<body>
<h1>Horizontally aligned element</h1>
<div>
A horizontally aligned text with the CSS justify-content property.
</div>
</body>
</html>
Result
In the next example, we align the text of the <div> to the center with the CSS text-align property set to its "center" value. Also, we specify padding-top.
Example of horizontally centering the content of a <div> with the text-align property:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
div {
border: 3px solid lightblue;
height: 80px;
text-align: center;
padding-top:10px;
}
</style>
</head>
<body>
<h1>Horizontally aligned element</h1>
<div>
A horizontally aligned text with the CSS text-align property
</div>
</body>
</html>
Example of horizontally centering the <p> and <span> elements of a <div>:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
div {
border: 3px solid lightblue;
height: 80px;
padding-top: 10px;
}
p {
margin: 0 auto 30px;
border: 1px solid lightgreen;
width: 250px;
}
span {
display: block;
margin: 0 auto;
border: 1px solid green;
max-width: 200px;
}
</style>
</head>
<body>
<h1>Horizontally aligned elements</h1>
<div>
<p>A horizontally aligned text.</p>
<span>A horizontally aligned text.</span>
</div>
</body>
</html>
In the end, we want to present a way of centering the content within a <div> both horizontally and vertically. Here, besides the justify-content and display (with "flex") properties, you need the align-items property which will set the vertical alignment to the center.
Example of centering the content of a <div> both horizontally and vertically:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
div {
border: 2px solid lightblue;
height: 100px;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<h1>Horizontally and vertically aligned element</h1>
<div>
Both horizontally and vertically aligned text with the CSS justify-content property.
</div>
</body>
</html>