Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

html - Center and bottom-align flex items

I have a flex container (the blue square) with the following properties:

display: flex;
justify-content: center;
align-items: center;
flex-wrap: nowrap;

Therefore, its children (the light blue squares) arrange themselves as you see below. However, I'd like to add another child (the green square) out of the normal flow and position it relative to its parent. To position it as you see below, I'd ideally write something like bottom: 20px; and margin: auto;.

enter image description here

I tried to play around with z-index to no avail. How should I approach this? Should I resort to creating another parent element?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Below are five options for achieving this layout:

  1. CSS Positioning
  2. Flexbox with Invisible DOM Element
  3. Flexbox with Invisible Pseudo-Element
  4. Flexbox with flex: 1
  5. CSS Grid Layout

Method #1: CSS Positioning Properties

Apply position: relative to the flex container.

Apply position: absolute to the green flex item.

Now the green square is absolutely positioned within the flex container.

More specifically, the green square is removed from the document flow but stays within the bounds of the nearest positioned ancestor.

Use the CSS offset properties top, bottom, left and right to move the green square around.

flex-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: nowrap;
  position: relative;
  border: 4px solid blue;
  height: 300px;
  width: 300px;
}
flex-container > flex-item:first-child {
  display: flex;
}
flex-container > flex-item:first-child > flex-item {
  border: 4px solid aqua;
  height: 50px;
  width: 50px;
  margin: 0 5px;
}
flex-container > flex-item:last-child {
  position: absolute;
  bottom: 40px;
  left: 50%;
  transform: translateX(-50%); /* fine tune horizontal centering */
  border: 4px solid chartreuse;
  height: 50px;
  width: 50px;
}
<flex-container>
    <flex-item><!-- also flex container -->
    <flex-item></flex-item>
    <flex-item></flex-item>
    <flex-item></flex-item>
    </flex-item>
    <flex-item></flex-item>
</flex-container>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...