CSS - Center a text or an element with position relative

← PrevNext →

Let us assume, I have few elements on my web page like a DIV and two P elements. The <div> is the parent element with position: absolute and the two <p> elements are the child elements with position: relative. How do I center the <p> elements with relative position? Its simple.

In this case, the text-align: center option may not work, since the position of the child (<p>) element is relative to its parent element. You can try it yourself and see the result.

I am sharing two methods here.

1st method: Here I am using the margin attribute to center the <p> elements.

<!DOCTYPE html>
<html>
<head>
<style>
  div {
    position: absolute;
    border: solid 1px #ddd;
    width: 100%;
    top: 0;
    left: 0;
  }
  
  p {
    position: relative;
    width: 100px;
    
    margin: 0 auto;     /*  center all P elements with relative position */
  }
</style>
</head>

<body>
  <div>
    <p>  Arun Banik    </p>
    <p>  Samual Jackson   </p>
  </div>
</body>
</html>
Try it

2nd method: In this method, I am using the left and transform attributes.

<!DOCTYPE html>
<html>
<head>
<style>
  div {
    position: absolute;
    border: solid 1px #ddd;
    width: 100%;
    top: 0;
    left: 0;
  }
  
  p {
    position: relative;
    width: 100px;
    
    left: 50%;
    transform: translateX(-50%);
  }
</style>
</head>

<body>
  <div>
    <p>  Arun Banik    </p>
    <p>  Samual Jackson   </p>
  </div>
</body>
</html>
Try it

If parent element has display: flex

In the above examples, the <p> elements or the child elements were shown vertically. We can also show child elements horizontally by setting the parent’s display property as flex. And, using margin: auto we can center the elements.

<!DOCTYPE html>
<html>
<head>
<style>
  div {
    position: absolute;
    border: solid 1px #ddd;
    width: 100%;
    top: 0;
    left: 0;

    display: flex;
  }
  
  p {
    position: relative;
    width: 100px;
    
    margin: 0 auto;     /*  center all P elements with relative position */
  }
</style>
</head>

<body>
  <div>
    <p>  Arun Banik    </p>
    <p>  Samual Jackson   </p>
  </div>
</body>
</html>
Try it

Be nice and stay safe. Thanks for reading.

← PreviousNext →