问题
How to centralize this span under the avatar using flex?
The avatar image is well centralized if I remove the span, but when I insert the span, even with display:block
it displays on the right side.
Here is my HTML:
<ion-navbar *navbar>
<ion-avatar item-center>
<img src="img/bill-gates-avatar.jpg">
<span>Bill Gates</span>
</ion-avatar>
</ion-navbar>
<ion-content padding>
Content here...
</ion-content>
That is my SCSS:
.tabs {
ion-navbar-section {
min-height: 16.6rem;
}
.toolbar {
min-height: 170px;
}
ion-avatar {
display: flex;
justify-content: center;
align-content: center;
}
ion-avatar img {
max-width: 8rem;
max-height: 8rem;
border-radius: 5rem;
border: 2px solid color($colors, light);
}
}
回答1:
An initial setting of a flex container is flex-direction: row
, meaning items will align horizontally by default. For vertical alignment, override the default with flex-direction: column
.
ion-avatar {
display: flex;
flex-direction: column; /* align flex items vertically */
justify-content: center; /* center items vertically, in this case */
align-items: center; /* center single-line items horizontally, in this case */
align-content: center; /* center multi-line items horizontally, in this case */
}
Note that when you switch flex-direction
, keyword alignment properties such as align-items
and justify-content
switch direction, as well.
Alternatively, you can center the avatar by removing it from the normal flow with absolute positioning. However, in a flex container, this may not work well in some browsers.
Learn more about flex alignment along the main axis here:
- In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?
Learn more about flex alignment along the cross axis here:
- How does flex-wrap work with align-self, align-items and align-content?
回答2:
The Answer above is the best way to do it if you want vertical, and center positioning throughout the entire parent container, but if you want to style "bill gates" as a single child of the parent container, you can simply style him like...
.bill-gates{
margin: auto;
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
}
来源:https://stackoverflow.com/questions/37923079/center-span-element-under-an-image-element-ionic2