-1

How can I center one div in the middle of the screen? Mainly I have problems with horizontal centering. If I use absolute positioning, then only the first line is in the middle horizontally. My code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>hey I am a title</title>
    <style>
        html, body {width: 100%; height: 100%;}
        .t7{
            text-align: center;
            position: relative; top: 50%;}
    </style>
</head>
<body>

<!-- this code centers an element in the middle of the screen -->


<div class="t7">
    I am a text in the middle of the screen.
    <br>
    second line
    <br>
    third line
    <br>
    fourth line
    <br>
    fifth line
</div>

</body>
</html>

Thank you.

Jan
  • 11
  • 4
  • `margin 0 auto;` to center the `
    ` in your example, though of course if it takes up 100% width then centering it is meaningless. To center the text within the div itself you'd use `text-align: center;` (which you already are).
    – Raxi Jan 05 '22 at 11:16
  • Do you want to centre the "box" with left aligned text or do you want to centre the text itself within the box? – Martin Jan 05 '22 at 11:18
  • @Raxi: margin: 0 auto; didn't solve the problem. Could you please send whole html code? – Jan Jan 05 '22 at 11:20
  • @Martin: The box both horizontally and vertically. Thank you. – Jan Jan 05 '22 at 11:21

2 Answers2

-1

Check this out! I guess this is what you want :)

enter image description here

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>hey I am a title</title>
  <style>
    html,
    body {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .t7 {
      text-align: center;
    }
  </style>
</head>

<body>

  <!-- this code centers an element in the middle of the screen -->

  <div class="t7">
    I am a text in the middle of the screen.
    <br> second line
    <br> third line
    <br> fourth line
    <br> fifth line
  </div>

</body>

</html>
Harry Tom
  • 384
  • 1
  • 3
  • 14
-1

Try this code :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>hey I am a title</title>
    <style>
        html, body {width: 100%; height: 100%;}
        .t7{
            text-align: center;
            position: relative; top: 50%;}
    </style>
</head>
<body>

<!-- this code centers an element in the middle of the screen -->


<div style="text-align:center">
    I am a text in the middle of the screen.
    <br>
    second line
    <br>
    third line
    <br>
    fourth line
    <br>
    fifth line
</div>

</body>
</html>
pooja
  • 81
  • 3