1

I’m using Flexbox, I want to create container that contains two divs in one row. One of them should be horizontally centered(relatively to container) and second one should be on the left(like it wouldn't be justified). Is there any solution that doesn’t require a third, hidden div?

Unfortunately both of divs don’t have specified width.

Here is the structure of html:

<div class="container">
  <div>Div on the left</div>
  <div>Horizontally centered div</div>
</div>
Pete
  • 57,112
  • 28
  • 117
  • 166
Mr. XYZ
  • 23
  • 7
  • What do you mean by "Horizontally centered", centred on the entire page? Or centred in the left over space to the right of the first div? – DBS May 10 '18 at 13:04
  • 1
    You could use an pseudo element on the container to create that third element – Pete May 10 '18 at 13:05
  • @DBS centered in the whole container(like it would have absolute position) if there is enough space(big device). In the case of small device when there is not much free space it should be centered in the left over space. Have no idea is it possible. :) – Mr. XYZ May 10 '18 at 13:11
  • the duplicate deal with right alignment but you simply do the same for the left ... – Temani Afif May 10 '18 at 13:16

2 Answers2

1

You can do it with the positioning:

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

.container > div:first-child {
  position: absolute;
  left: 0;
}
<div class="container">
  <div>Div on the left</div>
  <div>Horizontally centered div</div>
</div>
VXp
  • 11,598
  • 6
  • 31
  • 46
  • I'll do it that way if don't find other solution. I though that might be a trick that lets justify only one specific element. Something like a `align-self` – Mr. XYZ May 10 '18 at 13:15
  • @Mr.XYZ you can play with margin auto : https://jsfiddle.net/h5yun8ju/1/ – Temani Afif May 10 '18 at 13:18
  • @Mr.XYZ It's possible with the `align-self: flex-start` if you don't mind having them on separate rows. – VXp May 10 '18 at 13:25
  • @TemaniAfif I've already played with it, but without any positive result. Unfortuntaely Your solution kind of works, but because of `width: 0` and `white-space: nowrap` it works only with the plain text(displaying images, background etc doesn't work), but thank you for your help @VXp both of divs have to be in one row – Mr. XYZ May 10 '18 at 13:34
1

this is not perfect, but you can do this.

.container {
  display: flex;
}

.container > div{
   margin-right: auto;
}

.container > div:first-child {
  min-width:0;
  width:0;
  white-space:nowrap;
}
<div class="container">
  <div>Div on the left</div>
  <div>Horizontally centered div</div>
</div>
patelarpan
  • 7,188
  • 2
  • 20
  • 25