ArtStyle.Qwerty
ArtStyle.Qwerty

Reputation: 41

HTML align center with respect to the element, not the webpage layout

<!DOCTYPE html>
<html>
<head>
<title>HTML demo</title>
</head>
<body>

<div style="text-align:left;">
A B C D E F G 
</div>

<div style="text-align:center;">
D
</div>

</body>
</html>

What should I do if I want the second element D is right below (centered) A B C D E F G? My way, the D is at the center of the webpage.

Upvotes: 0

Views: 37

Answers (2)

Johannes
Johannes

Reputation: 67758

A second solution: You can wrap a container element around those divs and apply display: inline-flex, flex-direction: column; and align-items: center; to that container.

display: inline-flex, limits the width of the container to the contents, flex-direction: column; places the children below each other and and align-items: center; centers the contents inside the children elements. You won't need the inline text-alignments in this case.

.container {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
}
<!DOCTYPE html>
<html>

<head>
  <title>HTML demo</title>
</head>

<body>
  <div class="container">
    <div>
      A B C D E F G
    </div>
    <div>
      D
    </div>
  </div>
</body>

</html>

Upvotes: 0

Temani Afif
Temani Afif

Reputation: 272891

put both of them inside an inline-block element:

<!DOCTYPE html>
<html>
<head>
<title>HTML demo</title>
</head>
<body>
<div style="display:inline-block">
<div style="text-align:left;">
A B C D E F G 
</div>

<div style="text-align:center;">
D
</div>
</div>
</body>
</html>

Upvotes: 3

Related Questions