text-align: center
is indeed the way to go; it's merely a matter of finding a selector that will only target the element that you're after. Based on your above example, all you should need is .element
:
.element {
text-align: center;
}
<div class="parent">
<div class="other">
some stuff that should not be centered
</div>
<div class="other2">
some stuff that should not be centered
</div>
<div class="element">
some stuff that needs to be centered
</div>
</div>
Assuming there are multiple elements with the class element
you can use the child combinator selector (>
) as .parent > .element
to specifically target the one that is a direct child of .parent
:
.parent > .element {
text-align: center;
}
<div class="parent">
<div class="other">
some stuff that should not be centered
</div>
<div class="other2">
some stuff that should not be centered
</div>
<div class="element">
some stuff that needs to be centered
</div>
</div>
You could also use a pseudo-selector like :nth-of-type
with .parent > div:nth-of-type(3)
, which would target the third <div>
child of .parent
, and thus achieve the same result:
.parent > div:nth-of-type(3) {
text-align: center;
}
<div class="parent">
<div class="other">
some stuff that should not be centered
</div>
<div class="other2">
some stuff that should not be centered
</div>
<div class="element">
some stuff that needs to be centered
</div>
</div>
If you're looking to center the whole element and not just the text, you're looking for margin: 0 auto
, though note that a <div>
element occupies the full width
of the line by default, so you'll want to set a width
on the element as well. Ideally this would be width: fit-content
, to ensure that the element only occupies as much space as the text:
.parent > .element {
margin: 0 auto;
width: fit-content;
}
<div class="parent">
<div class="other">
some stuff that should not be centered
</div>
<div class="other2">
some stuff that should not be centered
</div>
<div class="element">
some stuff that needs to be centered
</div>
</div>
Note that margin
only applies to block-level elements (which <div>
is by default), so if you manually changed this with display: inline-block
(or you're using a <span>
), you'll need to additionally set display: block
.