-3

center div

I want to have a div which for example has a width of 50%. The div should then be centered horizontally. The Text within the div should be aligned left, just like in the photo aboth.

My HTML body code:

<body>
    <div class="navbar">Navbar</div>
    <div class="content">
        <div class="text1">Some Text</div>
        <div class="text2">More text</div>
    </div>
</body>
LoGRiTEY
  • 1
  • 1

2 Answers2

-1
<body>
<header>
    <nav>
        <h1>Nav</h1>
    </nav>
</header>
<main>
    <div>
        <h1>Hi</h1>
        <p>Hi</p>
    </div>
</main>
      body {
            width: 1024px;
            height:  768px;
            margin-left: auto;
            margin-right: auto;
            border: 1px solid black;
       }
       header {
            display: flex;
            align-items: centre;
            padding-top: 20px;
            padding-bottom: 20px;
            justify-content: left;
        }


        nav {
            flex: 2;
            justify-content: left;
            
        }

        div {
            width: 50%;
            min-height: 384px;
            border: 2px solid black;
            text-align: left;
            margin: auto;
            
        }
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 20 '21 at 20:56
-1

position: absolute;left: 50%;top: 50%;transform:translate(-50%,-50%); The code above is used to center an HTML element in its relative parent div

body {
  background: #333;
  color: #eee;
  position: relative;
  text-align: center;
}

.content {
  width: 50%;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: red
}
<body class="body">
  <div class="content">
    <div class="text1">Some Text</div>
    <div class="text2">More text</div>
  </div>
</body>
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 20 '21 at 19:44
  • I already added additional comment – Web Developer Nov 22 '21 at 09:04