Sobes.tech
Junior — Middle

Could you give an example of how to center a div element on a page using CSS?

sobes.tech AI

Answer from AI

To center a <div> element on a page using CSS, there are several methods. One of the simplest and most versatile is to use Flexbox:

body, html {
  height: 100%;
  margin: 0;
}

.container {
  display: flex;
  justify-content: center; /* horizontally */
  align-items: center;    /* vertically */
  height: 100vh;          /* container height - full screen */
}

.centered-div {
  width: 200px;
  height: 100px;
  background-color: lightblue;
}

And HTML:

<div class="container">
  <div class="centered-div">Centered block</div>
</div>

This method aligns the nested block both vertically and horizontally in the center of the screen.

Another way is to use absolute positioning with transformation:

.centered-div {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 200px;
  height: 100px;
  background-color: lightcoral;
}

This method also centers the element relative to the browser window.

Could you give an example of how to center a div… - sobes.tech