Q:

How to align a DIV horizontally center using CSS

0

How to align a DIV horizontally center using CSS

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the CSS margin property

If you would like to center align a <div> element horizontally with respect to the parent element you can use the CSS margin property with the value auto for the left and right side, i.e. set the style rule margin: 0 auto; for the div element. The auto value automatically adjusts the left and right margin and horizontally center align the div element's block box.

However, this solution will work only when the width of the parent element is more than the containing div element that you want to align. Let's check out an example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Horizontally Center Align Div Using CSS</title>
<style>
	.container {
		width: 80%;
		margin: 0 auto;
		padding: 20px;
		background: #f0e68c;
	}
</style>
</head>
<body>
    <div class="container">
		<h1>This is a heading</h1>
		<p>This is a paragraph.</p>
	</div>
</body>
</html>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now