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.
Defined Width
There are three popular methods to do this, they are:
Automatic Margin
#inner {
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-left
and 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.
Absolute Position
#outer {
position: relative;
width: 100%;
}
#inner {
left: 50%;
margin-left: -100px; /* A metade de sua largura. */
position: absolute;
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.
#outer {
align-items: center;
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
}
#inner {
width: 200px; /* Ou a que você quiser. */
}
Variable Width
There are two ways to position with variable widths, the most compatible for this purpose is the use of inline-block
.
inline-block
#outer {
text-align: center;
width: 100%;
}
#inner {
display: inline-block;
}
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.
CSS Transforms
However, if you're only concerned with browsers that already support CSS3, you can do it in a more elegant and simple way.
#outer {
position: relative;
width: 100%;
}
#inner {
left: 50%;
position: absolute;
transform: translateX(-50%);
}
This also is for vertical placements . :)