How to absolutely center an element both vertically and horizontally in CSS

How to absolutely center an element both vertically and horizontally in CSS

Centering element in the middle of the screen improves user engagement, draws attention to key actions, enhances aesthetics, and maintains layout consistency across devices.

The two most common ways are using Flexbox method or position and transform method.

Using Flexbox

This is one of the simplest and most modern ways to center an element.

HTML

  <div class="parent">
    <div class="child">Centered Content</div>
  </div>

CSS

  .parent {
    display: flex;
    justify-content: center; 
    align-items: center;     
    height: 100vh;         
  }

display: flex; let the browser know that we intend the children to use flexbox for their layout.

justify-content: center; centers the child horizontally.

align-items: center; centers the child vertically.

height: 100vh; is used to make the parent element take up the full height of the viewport. (optional)

 

Using position and transform

This method works well for absolutely positioned elements.

HTML

  <div class="parent">
    <div class="child">Centered Content</div>
  </div>

CSS

  .parent {
    position: relative; 
    height: 100vh;
  }

  .child {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

position: relative; is used to make the parent element have a position, which is necessary for the child to be absolutely positioned.

height: 100vh; is used to make the parent element take up the full height of the viewport. (optional)

position: absolute; is used to make the child element absolutely positioned.

top: 50%; moves the child 50% from the top of the parent.

left: 50%; moves the child 50% from the left of the parent.

transform: translate(-50%, -50%); moves the child back by half of its own width and height, effectively centering it.

 

Conclusion

Flexbox is the most modern and flexible approach and can be used for both fixed and responsive layouts.

Position and transform is a widely used method for absolute positioning, especially when dealing with fixed layouts.

Both of these methods ensure the element is centered perfectly both vertically and horizontally.

Domains and Web Hosting

Maxer domain and web hosting

Virtual server

Get server with Digital ocean