What I have is the following:
I have an icon on the left that represents a product. Then in H1, I have a product category, and with an h2, I have a product name.
The icon, h1, and h2 are in a parent div with flex and align-items value of baseline. So the text is baseline aligned.
Due to the dynamic nature of how the page title here is retrieved, the icon has to be in this parent div that is baseline aligned.
How can I vertically center the icon within this parent div with flexbox? I know how to accomplish this with vertical alignment and setting line height, but I'd prefer a flexbox approach.
Parent:
.parent {
display: flex;
align-items: baseline;
}
HTML skeleton:
<div >
<div>Icon</div>
<div>Product Category</div>
<div>Product Name</div>
</div>
CodePudding user response:
Use baseline
and center
vertical alignment in combination
In the snippet below, I've added a wrapper div
to hold the text elements together which get aligned around their baseline
. The parent
div will align its children vertically center
, so that the icon and the text block will be nicely aligned.
.parent {
display: flex;
align-items: center;
font-family: sans-serif;
}
img {
border-radius: 100px;
margin-right: 8px;
}
.text {
display: flex;
align-items: baseline;
}
h3 {
font-size: 24px;
line-height: 32px;
}
p {
font-size: 16px;
line-height: 24px;
}
h3 p {
margin-left: 12px;
}
<div >
<img src="https://picsum.photos/50" alt="icon" />
<div >
<h3>Product Category</h3>
<p>Product Name</p>
</div>
</div>
CodePudding user response:
You can set align-self:center
on the icon if you cannot change the parent div's align-items
value to center
. Find below an example:
.parent {
display: flex;
align-items: baseline;
gap:1rem; /* added just for readability, you can remove it */
}
.parent div:first-child{
align-self:center;
}
<div >
<div>Icon</div>
<h1>Product Category</h1>
<h2>Product Name</h2>
</div>