Better center by margin:auto or text-align:center?

Asked

Viewed 685 times

1

Searching for good HTML practices, what is the best way to centralize?

I see that I can center the menu of a page for both options, but I wonder which is the best way and also which is the right way instead of just using one that works being wrong in some cases.

Let’s see the following code:

* { margin: 0; padding: 0; }

#container { background-color: lightblue;
             height: 200px; }

.menu { list-style: none;
	    margin: auto;
   	    width: 200px; }

.menu-item { display: inline-block; }

a { padding: 10px;
    background-color: green; }
<div id="container">
  <ul class="menu">
	<li class="menu-item"><a href="">Home</a></li>
	<li class="menu-item"><a href="">Work</a></li>
	<li class="menu-item"><a href="">Contact</a></li>
  </ul>
</div>

I can only center the menu by margin: auto; when I set a menu class width and this in some cases can make me have problems when the items exceed that size, just change the width: 200px; for width: 100px; that the items are overlapping other.

When I define the menu class without width I can center the menu by setting a text-align: center; at the top tag selector, which in this case is id #container. By doing this I can solve the problem of the number of items on the list that can change and even be of different sizes depending on the modifications you need to make, but I still wonder if this is the right way to do the alignment in the center.

* { margin: 0; padding: 0; }

#container { background-color: lightblue;
             height: 200px;
         text-align: center; } /* adicionado */

.menu { list-style: none;}
/* removido width: 200px e margin: auto */

.menu-item { display: inline-block; }

a { padding: 10px;
    background-color: green; }
<div id="container">
  <ul class="menu">
	<li class="menu-item"><a href="">Home</a></li>
	<li class="menu-item"><a href="">Work</a></li>
	<li class="menu-item"><a href="">Contact</a></li>
  </ul>
</div>

1 answer

1


According to the W3C

The CSS margin properties are used to generate space Around Elements. Follow the link

That is, the function of the "margin" property is to define space around the elements.

The "text-align property":

The text-align Property specifies the horizontal Alignment of text in an element. Follow the link

In short, it serves to align text horizontally.

Good practice is to use a resource according to its function. If your goal is to centralize text. You should use "text-Algin". Otherwise, use "margin".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.