Course Content
CSS Basic
0/1
CSS Selectors
0/1
CSS Comments
0/1
CSS Backgrounds
0/1
CSS Borders
0/1
CSS Outline
0/1
CSS Fonts
0/1
CSS Height and Width
0/1
CSS Margins and Paddings
0/2
CSS Icons
0/1
CSS Links
0/1
CSS Lists
0/1
CSS Tables
0/1
CSS Display Properties
0/1
CSS Max-Width Property
0/1
CSS Positioning Elements
0/1
CSS Z-Index Property
0/1
CSS Overflow
0/1
CSS Float
0/1
CSS Opacity
0/1
CSS Forms
0/1
CSS Dropdowns
0/1
CSS Buttons
0/1
CSS Media Queries
0/1
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; and margin-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 class center-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 centered div).
  • 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).