-2

Pretty common question I guess, but couldn't find any solution to fix it.

Code is:

<div class="container">
  <div class="first-item">A</div>
  <div class="second-item">B</div>
</div>

Should look like this:

enter image description here

first-item will be at middle and second-item should be at last.

What I've tried:

.container {
  display: flex;
  justify-content: center;
}

.container .second-item {
  align-self: flex-end;
}

How could I achieve it using flex or in any other way of css?

m4n0
  • 29,823
  • 27
  • 76
  • 89
rony36
  • 3,277
  • 1
  • 30
  • 42

2 Answers2

4

Almost: you just need to add a margin auto on the first element

.container {
  display: flex;
  justify-content: center;
}

.first-item {
  margin: auto;
}
.second-item {
  align-self: flex-end;
}

Codepen demo

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
  • In your Codepen, change "B" into "Lorem Ipsum" and you'll see "A" is not in the center. – Gerard Oct 31 '18 at 10:07
  • A is centered with respect of the space available. If the second element is larger this space decreases. And, as per the OP image, the X is centered on the available space (not the full width). A solution with position absolute is fine if you know what you're doing because it could cause overlapping elements easier (B is removed form the flow) – Fabrizio Calderan Oct 31 '18 at 10:09
  • I doubt that's OP's requirement. But if it is, I'm sure OP will accept your solution because it's the cleanest one. – Gerard Oct 31 '18 at 10:12
  • What is the `align-self: flex-end;` on the second item for? The `margin: auto` already seems to do the trick. Is this for (other) browser support? (I'm using Chrome) – WoodrowShigeru Apr 18 '23 at 10:12
2

You can try that,

.container {
  display: flex;
  justify-content: center;
}

.container .second-item {
  right: 0;
  position: absolute;
}
<div class="container">
  <div class="first-item">A</div>
  <div class="second-item">B</div>
</div>
codesayan
  • 1,705
  • 11
  • 22