Yixen Lim
Yixen Lim

Reputation: 3

Center a div in HTML

I need to put two textarea inline and center both of them. However, I cannot find a way to center them after making them side by side. Is there anyway I can do it?

<!DOCTYPE html>
<html>

<head>
  <style>
    .inline-div {
      display: inline-block;
    }
  </style>
</head>

<body>

  <div class="inline-div">
    <p align="center">Input:</p>
    <textarea id="display_new_language"></textarea>
  </div>
  <div class="inline-div">
    <p align="center">Information:</p>
    <textarea id="display"></textarea>
  </div>

</body>

</html>

Upvotes: 0

Views: 141

Answers (2)

Vishal
Vishal

Reputation: 26

Add Parent DIV to both inline elements and give css text-align:center as shown below:

.inline-div {
  display: inline-block;
}

.center-div {
  text-align: center;
}
<div class="center-div">
  <div class="inline-div">
    <p align="center">Input:</p>
    <textarea id="display_new_language"></textarea>
  </div>
  <div class="inline-div">
    <p align="center">Information:</p>
    <textarea id="display"></textarea>
  </div>
</div>

Upvotes: 1

Imran Rafiq Rather
Imran Rafiq Rather

Reputation: 8098

Try with flexbox. Create a wrapper div (In this case body element) and use the following CSS.

body{
  display:flex;
  justify-content:center;
}

Note: With this approach, You don't need inline-block property on .inline-div elements.

<!DOCTYPE html>
<html>

<head>
  <style>
    body {
      display: flex;
      justify-content:center;
    }
  </style>
</head>

<body>

  <div class="inline-div">
    <p align="center">Input:</p>
    <textarea id="display_new_language"></textarea>
  </div>
  <div class="inline-div">
    <p align="center">Information:</p>
    <textarea id="display"></textarea>
  </div>

</body>

</html>

Like I mentioned, you can create a wrapper div around your .inline-div (in case you don't want to directly set the flex property on body).

HTML:

<main class="flexWrapper">
  <div class="inline-div">
    <p align="center">Input:</p>
    <textarea id="display_new_language"></textarea>
  </div>
  <div class="inline-div">
    <p align="center">Information:</p>
    <textarea id="display"></textarea>
  </div>
</main>

CSS:

    .flexWrapper{
      display: flex;
      justify-content:center;
    }

Upvotes: 1

Related Questions