About Lesson
Horizontal Centering (margin and auto):
Definition:
Horizontal centering using the margin property and the auto value is a CSS technique used to center block-level elements horizontally within their containing parent element. This method is commonly used for responsive design to ensure that content appears centered across different screen sizes.
Syntax:
HTML
selector {
margin-left: auto;
margin-right: auto;
/* or shorthand: margin: 0 auto; */
}
margin-left: auto;
andmargin-right: auto;
together horizontally center the element.- The shorthand
margin: 0 auto;
achieves the same result more succinctly.
Example:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh; /* Set the body height to 100% of the viewport height */
}
.center-horizontally {
width: 50%; /* Set the width of the centered element */
background-color: lightblue;
padding: 20px;
}
</style>
<title>Horizontal Centering Example</title>
</head>
<body>
<div class="center-horizontally">
<p>This content is centered horizontally.</p>
</div>
</body>
</html>
output:
Explanation:
a. Html Structure:
- Create a basic HTML file with a
div
element having the classcenter-horizontally
. This element will be centered horizontally.
b. CSS Styles:
- Set the body’s margin and padding to
0
to ensure no default spacing. - Use
display: flex;
to make the body a flex container. justify-content: center;
horizontally centers the child elements (in this case, the centereddiv
).align-items: center;
vertically centers the child elements.- Set the height of the body to
100vh
(viewport height) to center the content vertically. - In the
.center-horizontally
class, set the width, add some styling (e.g., background color, padding).
This approach works well for block-level elements. The margin: 0 auto;
on the centered element will evenly distribute the remaining space on the left and right, effectively centering it horizontally within the flex container (the body in this case).