I have a div with some child elements that I wish to center. I do, however, only wish to center elements with a specific class and not all elements in the div. The usual method would be to apply
Code:
text-align:center;
to the parent element, however, that triggers all its containing elements. How would I trigger only certain types of elements or elements with a specific class inside that div to only center some of the elements?
Hello CaptainB,
Since the elements you want centered have a class, can you can leave the parent at default text-align: left; and use this method to center the specific class instead?
To center an element you need three things:
a valid DocType
an element with a width
that elements right/left margins set to auto
kelisaid, text-align: center; on the classes them selves would only center their content, not the classes.
Tempz: that does unfortunately not work. I suspect that for centering the contents of the a-tags but not the tags itself.
The elements that I want to center are inline-block elements with a dynamic width, so the trick with margins does not work.
To be a little more clear I have posted my code below. The a-tags are childs of a div container with a fixed width. I want the a-tags to be centered within their container but I do not want to center the rest of the container's content, i.e. the h2.
Code:
<div class="showHideElement innerElement overview">
<h2>Vælg hvad du vil gøre</h2>
<a class="overviewButton btn1 lightbtn" ><span id="writeArticle"></span>Skriv ny artikel</a>
<a class="overviewButton btn2 lightbtn"><span id="administerArticles"></span>Administrer artikelarkiv</a>
</div>
(don't mind about the empty span tags - they are used for something).
Thank you, Excavator.
I have thought about that solution as kind of a last resort; the reason why I would like to avoid doing it that was is that the code should be reuseable. If I do it like you suggest, I would have to left-align all other elements instead of just centering the before mentioned elements, ala I would have to remember to left align all other content that goes into the container. But it could be that this would be the only way to do it?
Thank you, Excavator.
I have thought about that solution as kind of a last resort; the reason why I would like to avoid doing it that was is that the code should be reuseable. If I do it like you suggest, I would have to left-align all other elements instead of just centering the before mentioned elements, ala I would have to remember to left align all other content that goes into the container. But it could be that this would be the only way to do it?
Instead of centering the class, put what needs centered in a containing element so you can use text-align: center;
Something like this?