1

How can I center align text in a div with the following structure:

.centerText {
    position: absolute;
    left: 100px;
    top: 20px;
    text-align: center;
    font-size: 25px;
}
<div class="centerText">Hello World</div>

Doing so still aligns the text to the left side; 100px from the left.

3 Answers3

0

Try this.

.centerText {
    position: absolute;
    left: 50%;
    top: 20px;
    font-size: 25px;
    transform: translate(-50%);
}
<div class="centerText">Hello World</div>
  • Well i need to use the left: 100px property as it dynamically changes –  Mar 31 '18 at 04:38
0

To have the text centered while still using left: 100px you need to add right: 100px to automatically set the width of your div and have the same amount of spacing on both sides therefore centring the div too.

.centerText {
    position: absolute;
    left: 100px;
    right: 100px;
    top: 20px;
    text-align: center;
    font-size: 25px;
}
<div class="centerText">Hello World</div>
Omar Tanti
  • 1,103
  • 1
  • 12
  • 21
  • When the value becomes greater than 50% of the parent width. It no longer works –  Mar 31 '18 at 05:01
  • It does not mean that it yields the same result as your code but. And which value becomes greater than 50% of the parent width? can you please also include the parent div in your question too than? – Omar Tanti Mar 31 '18 at 05:07
0

to center a text or an element inside a div it has to have a larger width,

take a look at : calc() https://www.w3schools.com/cssref/func_calc.asp

you can set the width of the div according to the page ( dynamically ) and remove the 100px from the left ( and another 100px from the right ) so the div will be centered and the text too ( with text-align:center )

.centerText {
    position: absolute;
    left: 100px;
    top: 20px;
    text-align: center;
    font-size: 25px;
    background: red;
    width: calc(100% - 200px);
}
<div class="centerText">Hello World</div>
Taki
  • 15,354
  • 3
  • 20
  • 39