1

I have made a div of fixed height and I want the text to align both vertically and horizontally in the div.

I tried using margin:auto and text-align but it didn't help.

I am beginner HTML/CSS.

 <!DOCTYPE html>
    <html>
    <body>
    
    <div style="background-color:black;color:white;padding:20px; height:400px;">
      <h2>London</h2>
      
    </div>
    
    </body>
    </html>
Community
  • 1
  • 1
Dhrub Kumar
  • 105
  • 8

3 Answers3

1
h2 {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
depiction
  • 772
  • 6
  • 16
  • Actually we should have got answer without using transform but actually it is not aligning perfectly in center. Why? And What is the actual role of transform? – Dhrub Kumar Aug 27 '16 at 05:18
  • 1
    Position with top left of 50% sets the top left corner of the h2 dead center within it's parent. Transform is used to move it back 50% relative to the h2's dimensions so it visually appears in the middle. – depiction Aug 27 '16 at 05:23
0

Use this

.align{
  text-align: center;           
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}
Prifulnath
  • 463
  • 7
  • 24
0

h2 {
    position: absolute;
    top: 50%;
    left: 50%;
}
    <div>
      <h2>London</h2>

    </div>
Roma
  • 272
  • 1
  • 12