-1

I tried to center divS using "margin: auto" and I even set is as important but it is not working. Then i tried center tag:

<center><div></div></center>

It worked!

So how can i center the div using css and not html? Here is my code thanks:

<div style="margin: auto !important;">
<h1 style="color: yellow">Do you want to build a snowman?</h1>
<div class="head"></div>
<div class="eye1"></div>
<div class="eye2"></div>
<div class="nose"></div>
<div class="mouth"></div>
<div class="smile"></div>
<div class="body"></div>
<h2 style="color: yellow">yes?</h2>
</div>
Cyberlicious
  • 49
  • 1
  • 5
  • 1
    The [obsolete `
    `](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/center) and `margin:auto` are used to achieve different things. The former makes the container *content* centered. The latter centers the *container* itself, but that obviously only has an effect on containers that do not span the whole width already. So what are you trying to achieve exactly? Are you looking for [`text-align:center`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align)?
    – str Dec 19 '20 at 15:20
  • 1
    `
    ` is obsolete, don't use it
    – Alon Eitan Dec 19 '20 at 15:20

3 Answers3

0

Your container is already full width you can consider adding text-align:center to your code to make the text centered, or if you want to decrease the width of the div you can go ahead and do it because margin:auto will take care of centering it.

Shrikantha Budya
  • 646
  • 1
  • 4
  • 15
0

just add text-align: center to your parent div instead of margin and it will work.

.container{
  text-align: center;
}
<div class=container>
<h1 style="color: yellow">Do you want to build a snowman?</h1>
<div class="head">head</div>
<div class="eye1">eye1</div>
<div class="eye2">eye2</div>
<div class="nose">nose</div>
<div class="mouth">mouth</div>
<div class="smile">smile</div>
<div class="body">body</div>
<h2 style="color: yellow">yes?</h2>
</div>
0

h1{
  color: yellow;
}
div{
  color: #000;
}
.container{
  margin: 20px auto;
  text-align: center;
}
<div class="container">
<h1>Do you want to build a snowman?</h1>
<div class="head">A</div>
<div class="eye1">B</div>
<div class="eye2">C</div>
<div class="nose">D</div>
<div class="mouth">E</div>
<div class="smile">F</div>
<div class="body">G</div>
<h2 style="color: yellow">yes?</h2>
</div>

You actually solved the problem. You are averaging the divs you added, but you also had to average the contents of the divs inside. Good Night :)