I want to exclude the h2 element(inside the h2 div) so I can center the main title only. But when I use this command it aligns both titles to the center.
.container:not(.h2) {
display: flex;
justify-content: center;
align-items: center;
}
<div >
<h1>welcome</h1>
<div >
<h2>Hi</h2>
</div>
</div>
Need to align only one element.
CodePudding user response:
To use this approach you'll need to use the child combinator >
. This says "match the elements that are direct children of the .container
class and do not have the .h2
class"
.container > :not(.h2) {
display: flex;
justify-content: center;
align-items: center;
}
<div >
<h1>welcome</h1>
<div >
<h2>Hi</h2>
</div>
</div>
Your original CSS .container:not(.h2)
is saying "select an element that has both the .container
class and does not have the .h2
class" - .container
fits that so it applies the class to the whole div
.
In practice for this example you could just use text-align: center;
on your h1
, make different flexbox containers, or use more specific element selectors rather than using the parent .container
class.
CodePudding user response:
You are telling the .container class to center its children, which is why both elements are being centered.
Center text: In your case you just want to center the text, so we can just assign it the text-align:center property and remove the .container styling.
Center using Flexbox: This is what you used in your attempt, but you would have to re-structure your html.
Code using Flexbox:
.centerElement{
display: flex;
justify-content: center;
}
<div>
<div >
<h1>welcome</h1>
</div>
<div >
<h2>Hi</h2>
</div>
</div>
Code using text-align:
#welcomeText{
text-align:center;
}
<div>
<h1 id="welcomeText">welcome</h1>
<div>
<h2>Hi</h2>
</div>
</div>