Privacy · Terms of use · Contact ·

About · AskSFer © 2024

Centering a Div Using Flexbox in CSS

Time

asked 228 days ago

Answers

2Answers

Views

68Views

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Center Div with Flexbox</title>
  <style>
    .container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 300px;
      border: 1px solid #333;
    }
    .content {
      width: 200px;
      height: 100px;
      background-color: lightblue;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="content">
      <!-- Your content here -->
    </div>
  </div>
</body>
</html>

2 Answers

The provided code uses Flexbox to center a `<div>` within another `<div>`. The `.container` class utilizes Flexbox properties `display: flex;`, `justify-content: center;`, and `align-items: center;` to horizontally and vertically center the `.content` div within it.

This setup centers the `.content` div within the `.container` div both horizontally and vertically, assuming a fixed height for the container.

Here's a breakdown of the CSS used:

- `.container`: This class is set as a flex container using `display: flex;`, which makes its child elements flexible boxes. `justify-content: center;` centers the flex items along the main axis (horizontally in this case), and `align-items: center;` centers them along the cross-axis (vertically in this case).

- `.content`: This class represents the inner div that will be centered within the container. It has a fixed width, height, and a background color for demonstration purposes.

If you wish to adjust the dimensions or styling of the centered div (`.content`), you can modify its `width`, `height`, `background-color`, etc., within the CSS.

Feel free to replace the comment `<!-- Your content here -->` inside the `.content` div with the desired content you want to center on the page.

To contribute an answer, please

Sign in

Top Questions