I have this simple layout:
.container {
display: flex;
background-color: gray;
color: white;
align-items: center;
justify-content: center;
}
.el1 {
background-color: red;
}
.el2 {
background-color: blue;
}
<div class="container">
<span class="el1">element 1</span>
<span class="el2">element 2</span>
</div>
I want, that element2
is centered in the container first, and element1
is always next to it, regardless the size of element2
(element2
can have different sizes).
I tried with position: absolute
and auto margin on element2
and moving element1
left, but in this way, if element2
grows, I have to adjust also element1
.
What is the proper way of doing this?
3
Answers
You just need to reverse the order of the flex, you can use
flex-direction:row-reverse
in your caseI don’t how you prefer the "element 1" to be, but I’m assuming its width would be not as flexible as the "element 2". Have a look on code below, especially on the comment for the
.el1
width.This is maybe not the best way to achieve what you want, but it’s one possible way:
I added another, empty span which gets the same width as the left span in px for example, so the span in the middle will be centered horizontally. Of course you would have to adjust the width dependent of the content of the left span.
I’m sure, there are better solutions to this, but it may be helpful nevertheless.