How I Center a Div or Text in a Div in CSS

Written by: Darrielle Evans
Developer checklist graphic featuring a smiling young man with a short beard in a black shirt, surrounded by coding symbols and references to HTML and C++. The title highlights tips for landing a developer role in AI.

HOW TO LAND A DEVELOPER ROLE

A free checklist to help you stand out from human and AI competition and land a developer job.

Download Now
Laptop illustrating how to center div horizontally and vertically in CSS

Updated:

Published:

When I first started using CSS, I learned how to center a div using Flexbox, and that was all I used. It turns out there are many more ways to achieve this style in CSS.

Whether you're building a site from scratch or with the assistance of a website builder, it's essential to have a basic understanding of HTML and CSS to customize your page layouts. In addition to having that basic knowledge, it's also critical to know how you can achieve styling elements, such as learning to center divs vertically and horizontally.

Download Now: How to Land a Developer Role in
the World of AI [Free Checklist]

Most of the web pages I created at the beginning of my career were extremely limited due to my lack of knowledge of how powerful CSS is. The good news is you don’t have to make the same mistakes I did. I'm here to help you discover multiple methods for centering elements in CSS (and to share some hacks along the way).

Table of Contents

What is a div and why center a div?

One thing I struggled with as a beginner programmer when building a layout was how to arrange and style elements on the page.

Now I always ask myself:

  • Do I want the elements to overlap or have space between them?
  • Do I want some text on the page to be centered and the rest left-aligned?
  • Do I use plain CSS or a framework?

That's a lot of questions. Luckily, divs can help and have always been my go-to way to target my styles.

A div — short for content division elements — is a generic block-level HTML element. As the name implies, divs can divide your web pages into more digestible sections. By doing so, you can target them with CSS.

How to Center a Div in CSS

There are a few ways to center a div in CSS. And yes, it's possible to center div vertically and horizontally — though doing so vertically is a bit trickier.

I‘ll walk you through both of these methods below. Then, I’ll share how you can center a div vertically and horizontally — or even center a div within another div. (Spoiler: It's not as overwhelming as it sounds.)

How To Land a Developer Role in the World of AI

A free checklist to you help you stand out from the competition featuring Software Developer and YouTube Creator Tech With Tim.

  • Expert advice on how to build a portfolio
  • Top programming languages to learn
  • Resume building and interview tips
  • Resources to strengthen communication skills

    Download Free

    All fields are required.

    You're all set!

    Click this link to access this resource at any time.

    How to Center a Div Horizontally

    To center a div horizontally on a page:

    • Give the div a CSS class like center.
    • In your CSS code, type your .center CSS selector and open the style brackets.
    • Set the width of the element by either percentage or pixels, i.e., width: 50%; or width: 500px.
    • Set the margin property to auto. That way, the div will take up whatever width is specified in the CSS and the browser splits the remaining space equally between the margins on either side.

    Let’s look at a simple example of a CSS box model. Say you want to create a div with a brief paragraph inside of it. Here, I've given the div the class center, and assigned the margin value auto.

    Try It Yourself: Output of Centering a Div Horizontally

    The code module below is editable. Toggle between the HTML and CSS tabs, edit the code, and click rerun in the bottom right-hand corner.

    Did you notice that the margins are different from padding? I‘d use padding to create space between the div’s border and the paragraph inside of the div, which, in this case, is the inline element.

    If you want to learn more about the differences between these two properties, I encourage you to explore this post: CSS Margin vs. Padding: What's the Difference?

    How to Center a Div Vertically

    Now, I‘ll show you how to center a div vertically. It’s a bit more difficult, but not impossible.

    To center a div vertically on a page, you can use the CSS position property, top property, and transform property. Here's how:

    • Give the div a CSS class like center.
    • In your CSS code, type your .center CSS selector and open the style brackets.
    • Set the position of your div to absolute so that it’s taken out of the normal document flow.
    • Set the top property to 50%. This tells the browser to line up the top edge of the div with the center of the page vertically (ie. 50% down the page).
    • Then, set the transform property to translate(0, -50%).

    Note: I might've been able to skip the last step, but here’s the problem: Having the top edge of the div lined up in the middle of the page won’t center the div. I need to define one last property, the transform property.

    While there are several different transformation methods, I want to use the translate() method to move the div along the Y-axis of the page. I want to move the div 50% up from its current position. That will tell the browser to put the center of the div in the vertical center of the page.

    Try It Yourself: Output of Centering a Div Vertically

    The code module below is editable. Toggle between the HTML and CSS tabs, edit the code, and click rerun in the bottom right-hand corner.

    How to Center a Div Horizontally and Vertically

    Sometimes, centering a div horizontally or vertically isn‘t enough, and you’ll need to do both. To achieve this, I‘ll show you that you can follow almost the exact same steps outlined in the section above. You’ll use position, top, and transform. The only difference is that you'll also use the left property to center the div horizontally.

    Here's how:

    • Give the div a CSS class like center.
    • In your CSS code, type your .center CSS selector and open the style brackets.
    • Set the position of your div to absolute so that it’s taken out of the normal document flow.
    • Set the left and top properties both to 50%. This tells the browser to line up the left and top edge of the div with the center of the page horizontally and vertically (ie. 50% to the right and down the page).
    • Set the transform property to translate(-50%, -50%). This moves the div 50% to the left and up from its current position. That will tell the browser to put the center of the div in the center of the page.

    Try It Yourself: Output of Centering a Div Horizontally and Vertically

    The code module below is editable. Toggle between the HTML and CSS tabs, edit the code, and click rerun in the bottom right-hand corner.

    How to Center a Div Within a Div

    If you need to center a div within a div, you can do so in three ways. With each method, you can center the div within a div horizontally, vertically, or both.

    Method 1: Using the Position, Top, Left, and Margin Properties

    To horizontally and vertically center a div within a div on a page, you can use the position, top, left, and margin properties. However, to do so, you'll need to know the width and height of the divs.

    Here's how:

    • Wrap a div element in another div element in your HTML. Give the inner div a class like child and the outer div a class like parent.
    • In your CSS code, open the curly brackets for the class selector .parent.
    • Set the outer div’s height and width (i.e., 300px and 300px), then set the position property to relative.
    • You can now style the inner div. Open the curly brackets for the class selector .child.
    • Set the inner div's height and width (i.e., 100px and 100px), then set its position to absolute.
    • Now set the top and left properties both to 50%. This tells the browser to line up the left and top edge of the div with the center of the parent container horizontally and vertically.
    • Finally, set the margin property to -50px 0 0 -50px, so that the negative top and left margins are exactly half of the child element's height and width (in this case, -50px and -50px, respectively. This number will vary).

    Try It Yourself: Output of Centering a Div Within a Div

    The code module below is editable. Toggle between the HTML and CSS tabs, edit the code, and click rerun in the bottom right-hand corner.

    Method 2: Using the Position, Top, Left, and Transform Properties

    To horizontally and vertically center a div within a div whose height and width is unknown, you can use the transform property instead of the margin property. You'll still use the CSS position, top, and left properties.

    Here's how:

    • Wrap a div element in another div element in your HTML. Give the inner div a class like child and the outer div a class like parent.
    • In your CSS code, open the curly brackets for the class selector .parent.
    • Set the outer div’s height and width (i.e. 300px and 300px).
    • Set the position property to relative.
    • You can now style the inner div. Open the curly brackets for the class selector .child.
    • Set its position to absolute.
    • Now set the top and left properties to 50%.
    • Set the transform property to translate(-50%,-50%).

    With this method, you won't need to define the width or height properties. You also won't define the margin property. Instead, the transform property will push the div right and down from the container's edges. This ensures the child div is truly centered in the parent div.

    Try It Yourself: Output of Using the Position, Top, Left, and Transform Properties

    The code module below is editable. Toggle between the HTML and CSS tabs, edit the code, and click rerun in the bottom right-hand corner.

    Method 3: Using Flexbox

    Another strategy I use to center a div within a div is CSS Flexbox. Flexbox is an excellent method as it‘s responsive and doesn’t require margin calculations. However, there are a few additional steps to consider. I‘ll share those with you now. To center a div horizontally and vertically with Flexbox, here’s what you need to do.

    • In your CSS code, find your html and body selectors. Inside the curly brackets, set the height of both properties to 100%. (Note: You can set the height of the parent container to 100% as well, if you‘d like it to take up the whole viewport. For this demo, I’ll set the parent container to a specific height instead.)
    • Wrap a div element in another div element in your HTML. Give the inner div a class like child and the outer div a class like parent.
    • In your CSS code, open the curly brackets for the class selector .parent.
    • Set the outer div’s height (i.e., 200px).
    • Set the display property to flex. This will define the parent container as a flex container.
    • Set the align-items and the justify-content properties to center. This will tell the browser to center the flex item (the div within the div) vertically and horizontally.
    • We‘re technically done, but let’s still style the inner div. Open the curly brackets for the class selector .child.
    • Set the inner div's height and width (i.e., 100px and 100px).

    How To Land a Developer Role in the World of AI

    A free checklist to you help you stand out from the competition featuring Software Developer and YouTube Creator Tech With Tim.

    • Expert advice on how to build a portfolio
    • Top programming languages to learn
    • Resume building and interview tips
    • Resources to strengthen communication skills

      Download Free

      All fields are required.

      You're all set!

      Click this link to access this resource at any time.

      Try It Yourself: Output of Using Flexbox to Center a Div Within a Div

      The code module below is editable. Toggle between the HTML and CSS tabs, edit the code, and click rerun in the bottom right-hand corner.

      How to Center a Div With Unknown Sizes [2 Options]

      Around the late 2000s, device screens started varying a lot. We saw smartphones, tablets, etc., being introduced to the market. That’s when developing responsive content became even more critical.

      Devs wanted to ensure users had a good experience with their web pages regardless of their device choice. That’s where knowing how to center a div with an unknown size can come about.

      You can do so using flex or absolute positioning.

      Method 1: Using Flex

      • In your HTML, create a parent div. Then, inside the parent div, create a child div. This is also known as placing a div within a div.
      • In your CSS, create a .parent selector. We will customize a few properties inside the parent selector’s curly braces.
        • Set the display property to flex. This makes the parent a flex container.
        • Set the justify-content property to center. This centers the child horizontally along the main axis. 
        • Set the align-items property to center. This centers the child vertically along the cross-axis.
        • Set the height property to 100vh. This allows the parent to take up the full viewport height so it doesn’t take the content's height.

      Notice how I am only applying properties to the parent div for centering. This is because I have to use the parent div to target centering of the child div.

      Try It Yourself: Output of Using Flex to Center a Div with an Unknown Size

      The code module below is editable. Toggle between the HTML and CSS tabs, edit the code, and click rerun in the bottom right-hand corner.

      Method 2: Using Absolute Positioning & Transforms

      • In your HTML, create a parent div. Then, inside the parent div, create a child div.
      • In your CSS, create a .parent selector. Inside the parent selector’s curly braces, we are going to use the following three properties:
        • Set the position property to relative. I need this to control the absolute positioning of the child div.
        • Set the height property to 100vh. I am using this property to make the parent to the entire width of the viewport.
      • You can optionally set the min-height property to 100px.
      • In your CSS, create a .child selector. Inside the child selector’s curly braces, we are going to use the following three properties:
        • Set the position property to absolute. This removes the child from the document flow, which is necessary to avoid ruining the layout of other elements. 
        • Set the top property to 50% to position the child‘s top corner at the parent’s center.
        • Set the left property to 50% to position the child‘s top left corner at the parent’s center.
        • The most important property I am setting is transform. Set the transform property to translate(-50%, -50%). This moves the child back by half its width and half its height no matter what its actual size is.

      Try It Yourself: Output of Using Flex to Center a Div with an Unknown Size

      The code module below is editable. Toggle between the HTML and CSS tabs, edit the code, and click rerun in the bottom right-hand corner.

      How to Center a Stack of Div Elements [2 Methods]

      Knowing how to center a stack of divs can come in handy — like when I helped my brother revise his auto body shop website a few years ago. He wanted to show examples of his work using tiles of squares with the names of the cars and a description of the work completed, and he wanted the alignment to be centered.

      Whether showcasing examples, building a blog post, or showcasing a list of products, knowing how to center a stack of divs is essential.

      Here are the main two ways you can do it.

      Method 1: Using FlexBox

      • In my HTML, I created a div called parent-div. Then, inside the parent-div, I created a div called stack-of-divs. Finally, I created three divs inside of the stack of divs. The outer div is optional, but I recommend this structure to make your HTML more maintainable.
      • To target the stack-of-divs, the most important selector to customize in CSS is the parent-div. Set the display property to flex to make it a flex container.
      • Set the justify-content property to center to center the stack-of-divs container horizontally.
      • Set the align-items property to center to center the stack-of-divs vertically.
      • Set the height property to 100vh to allow the divs to fill the viewports.
      • The CSS on the stack-of-divs is optional and only used for styling purposes.

      Try It Yourself: Output of Using Flexbox to Center a Stack of Div Elements

      The code module below is editable. Toggle between the HTML and CSS tabs, edit the code and click rerun in the bottom right-hand corner.

      Method 2: Using CSS Grid

      • I used the same div structure in my HTML as the example above. I created an outer div called parent-div, a div to hold the stack of divs, and three individual divs.
      • In the CSS, inside the parent-div selector, I set the display property as grid instead of flex. This makes the container a grid, which allows the layout to be broken down into columns.
      • I set the place-items property to the center. With flex, we have to use two properties to center an item horizontally and vertically. However, we can achieve this using only the place-items property with the grid.
      • Set the height property to 100vh to make the container fill the viewport.

      Try It Yourself: Output of Using Css Grid to Center a Stack of Div Elements

      The code module below is editable. Toggle between the HTML and CSS tabs, edit the code and click rerun in the bottom right-hand corner.

      How to Center Text in Div in CSS

      Say I want to center text in a div in CSS. I can achieve this a few ways.

      The most common way is to use the text-align property to center text horizontally. Another way is to use the line-height and vertical-align properties. The final way exclusively applies to flex items and requires the justify-content and align-items properties. Using this method, you can center text horizontally, vertically, or both.

      I'll walk you through each of these methods below.

      How To Land a Developer Role in the World of AI

      A free checklist to you help you stand out from the competition featuring Software Developer and YouTube Creator Tech With Tim.

      • Expert advice on how to build a portfolio
      • Top programming languages to learn
      • Resume building and interview tips
      • Resources to strengthen communication skills

        Download Free

        All fields are required.

        You're all set!

        Click this link to access this resource at any time.

        How to Center Text in Div Horizontally [2 Methods]

        There are two ways to center text in a div horizontally.

        Method 1: Using the Text-Align Property

        Say you want to create a div with a short paragraph inside it. In most cases, you can center text horizontally in a div using the text-align property with the value center. Here's how:

        • Give the div a CSS class like center.
        • In your CSS code, type your .center CSS selector and open the style brackets.
        • Set the text-align property to center.

        Try It Yourself: Output of Center Text in a Div Using Text Align Property

        The code module below is editable. Toggle between the HTML and CSS tabs, edit the code, and click rerun in the bottom right-hand corner.

        Method 2: Using the Justify-Content Property

        There's one exception to the rule above: If using the display property to define your div as a flex container, then you can't use the text-align property to center text horizontally inside the div.

        Instead, you have to use the justify-content property with the value center.

        I'll show you how to create the same div element as above. Take these steps:

        • Give the div a CSS class like center.
        • In your CSS code, type your .center CSS selector and open the style brackets.
        • Set the display property to flex to make the div a flex container.
        • Set the justify-content property to center.

        Try It Yourself: Output of Center Text in a Div Using Justify-Content Property

        The code module below is editable. Toggle between the HTML and CSS tabs, edit the code, and click rerun in the bottom right-hand corner.

        How to Center Text in Div Vertically [3 Methods]

        Centering text vertically inside a div is a bit more complicated than horizontally, but there are a few ways to do it. I'll walk you through the different methods now.

        Method 1: Using the Padding Property

        In most cases, you can center text vertically in a div using the padding property. With this method, padding will take two values. The first value will set the top and bottom padding. The second will set the right and left padding.

        Follow along with me as I break this down:

        • Give the div a CSS class like center.
        • In your CSS code, type your .center CSS selector and open the style brackets.
        • Set the padding property to 50px 0.

        Since you want to center the text vertically, the first value, which stands for the top and bottom padding, can be any positive length or percentage value. The second value, which stands for the right and left padding, should be 0.

        Try It Yourself: Output of Centering Text in a Div Vertically Using Padding Property

        The code module below is editable. Toggle between the HTML and CSS tabs, edit the code, and click rerun in the bottom right-hand corner.

        Method 2: Using the Line-Height Property

        Usually, you can also center text vertically inside a div with the line-height property.

        In your HTML, add a paragraph element inside the div, then set the line-height property of the div equal to the height of the div.

        Here's how:

        • Give the div a CSS class like center.
        • In your CSS code, type your .center CSS selector and open the style brackets.
        • Define the height and line-height properties of your div to the same size (we use 150px in the example below).
        • Find or create your p CSS selector.
        • To center a paragraph with multiple lines, set the display property to inline-block.
        • Then, set line-height to normal and set vertical-align to middle.

        This last step ensures that the text inside the div is centered vertically, whether it's one line or multiple lines of text.

        Try It Yourself: Output of Centering Text in a Div Vertically Using Line-Height Property

        The code module below is editable. Toggle between the HTML and CSS tabs, edit the code, and click rerun in the bottom right-hand corner.

        Method 3: Using the Align-Items Property

        If you are using the display property to define your div as a flex container, then you can't use the method above to center text vertically within the div. Instead, you have to use the align-items property with the value center.

        Here's how:

        • Give the div a CSS class like center.
        • In your CSS code, type your .center CSS selector and open the style brackets.
        • Set display to flex to make the div a flex container.
        • To more clearly see that the text is vertically centered, define the height property as well (we use 150px for the example below). Otherwise, the flex container will only be as tall as it needs to be to contain the paragraph inside.
        • Then, set the align-items property to center.

        Try It Yourself: Output of Centering Text in a Div Vertically Using Align-Items Property

        The code module below is editable. Toggle between the HTML and CSS tabs, edit the code, and click rerun in the bottom right-hand corner.

        When to Use Each CSS Centering Method

        As you can tell by now, I am biased and probably would always recommend using the Flexbox method. However, the truth is you should choose the method that works best for your project.

        Let’s review the best use cases for each method:

        When you don’t know the size of a div: Use Flexbox.

        As we previously discussed, sometimes you don’t know the size of a div. In this case, Flexbox is the ideal method. Why? Because you don’t need to know the element's size thanks to Flexbox alignment flexibilities. There are also other properties that you can use, such as flex-grow or flex-basis, that can make your customization efforts even easier.

        When you have a stack of elements: Use a grid.

        A grid will be your best option when you have a stack of elements to consider. This is because you can control exactly how many rows and columns you want the elements to take up. You can also easily control complex stacking, such as overlapping elements.

        When centering a div within a div: Use text-align.

        Regarding centering text within a div, your best option will be to use the text-align property. This is because you can apply the property directly to the div you are targeting instead of using wrapper elements.

        When you want to focus on a single element: Use auto-margin.

        If you want to focus on a single element and center it horizontally, using the auto margin method to center will be the best option. This is thanks to its simplicity. However, remember to use this method, your element has to be block-level, and you must know the width.

        When you’re building a webpage: Use Flexbox.

        When building webpages, my goal is to always make them as responsive as possible, which is why I lean towards using the Flexbox method 95% of the time. Flexbox will usually give you the most versatility when styling your divs and other elements. So, if all else fails, make your div a flex container and apply the appropriate properties to center correctly.

        Build custom layouts with HTML and CSS.

        There you have it: Everything you need to know about how to center div vertically and horizontally, or beyond.

        As you can see, a bit of coding knowledge enables you to control and customize your layouts. Understanding the margin, position, and flex properties, for example, will enable you to center virtually any div or block element on a page.

        How To Land a Developer Role in the World of AI

        A free checklist to you help you stand out from the competition featuring Software Developer and YouTube Creator Tech With Tim.

        • Expert advice on how to build a portfolio
        • Top programming languages to learn
        • Resume building and interview tips
        • Resources to strengthen communication skills

          Download Free

          All fields are required.

          You're all set!

          Click this link to access this resource at any time.

          Related Articles

          A free checklist to help you stand out from human and AI competition and land a developer job.

            CMS Hub is flexible for marketers, powerful for developers, and gives customers a personalized, secure experience

            START FREE OR GET A DEMO