There are several ways.
These methods are split into "width defined" and "variable width" because it depends on your implementation need.
Some are semantically more recommended, but still do not work on almost any browser, others have been around for a long time and continue to be used because they have superior compatibility.
There are three popular methods to do this, they are:
margin: 0 auto;
width: 50%; /* Altere para o valor da largura desejada. */
What we did here was to report the
auto value for the properties of
margin-right that will automatically calculate the remaining space gap and magically center its element horizontally. It's important to remember that the same rule does not apply to vertically centering an object .
Internet Explorer 6: This version of Internet Explorer requires the addition of the
text-align: center; property in this code.
Internet Explorer 8: If you have compatibility issues with Internet Explorer 8, you may want to add the
display: table; property in this code.
margin-left: -100px; /* A metade de sua largura. */
width: 200px; /* O valor que você desejar. */
Although it uses negative and absolute position, this is the most compatible method that exists.
Caution: Take care that
position: absolute; does not compromise the integrity of your layout.
Although more recommended, this method is still being disseminated and remains as an experimental feature of browsers, so it is still very unstable to use.
width: 200px; /* Ou a que você quiser. */
There are two ways to position with variable widths, the most compatible for this purpose is the use of
What will make the
#inner element centered is the presence of the
text-align: center; property in
#outer . But it is important to note that our friend Internet Explorer 7 and lower ones do not support the
display: inline-block; property.
However, if you're only concerned with browsers that already support CSS3, you can do it in a more elegant and simple way.
This also is for vertical placements . :)