💻
HTML/CSS
  • Overview
  • How the Web Works
    • DNS, TCP/IP, HTTP, HTML
    • Anatomy of a Web Page
    • How a Web Page Gets Loaded
  • HTML/CSS intro
    • HTML
      • Boilerplate HTML
      • HTML Hierarchy
      • Meta Section
      • Text-formatting Elements
      • Image
      • Video
      • Anchor
      • Tables
      • Semantic Elements
    • CSS
      • Properties
      • Selectors
      • Box-Model
      • Block vs Inline
      • The Cascade
    • Layout
      • Container Elements
      • Grid vs Flexbox
      • Flexbox
      • Grid
  • Miscellaneous Topics
    • Background Image
    • Border-radius
    • Box-shadow
    • Centering Elements
    • Colors
    • Custom Properties
    • Forms
    • Typography
    • Units
  • Appendix
    • Google Fonts
    • Lorem Ipsum
    • HTML Cheatsheet
    • CSS Cheatsheet
    • Browser Support for HTML/CSS
    • unsplash.com (free images)
    • pexels.com (free images)
    • Chrome Default Stylesheet
  • Further Learning Resources
    • FE Mentor Challenges
    • Free Scrimba Courses
    • Kevin Powell Youtube
Powered by GitBook
On this page
  • Specific width with auto left and right margins
  • Using flex and center in both horizontal/vertical directions.
  • Resources

Was this helpful?

  1. Miscellaneous Topics

Centering Elements

PreviousBox-shadowNextColors

Last updated 3 years ago

Was this helpful?

You often want to center items on the page as a whole, or within a container element. There are two common techniques to achieve this goal.

Specific width with auto left and right margins

This technique works well when you know the width of the content to be centered.

  • set a width on the element

  • set the margin-left and margin-right to auto

  body {
    margin-left:auto;
    margin-right:auto;
    width:300px;
  }

Using flex and center in both horizontal/vertical directions.

Set the value of the display property to be flex in the column direction, and then center the items in both the horizontal and vertical directions.

body {
  display:flex;
  flex-direction:column;
  justify-content: center;
  align-items: center;
}

Resources

Centering in CSS: A Complete Guide | CSS-TricksCSS-Tricks
Logo