Using CSS flex, how do I get two items horizontal with each other at the top of a page, one aligned left, the other aligned center vertically?
I have margin left 0 for the first item. If I use margin auto for the other, the left edge of the item centers vertically, not the item itself.
Here’s one way with grid.
It all depends on what you expect to happen next as there are many possible scenarios involved but the above works for the use case illustrated.
There is no easy ‘natural way’ to centre something irrespective of what else is on the line that caters for all outcomes.
The centered text is centered within the DIV, not within the body which is what I’m trying to get. If the width of the DIV with the red background was 100%, the DIV was transparent and overlapped the other DIV, that would work, if that’s possible?
The left aligned text width is only about 200px, the centered text is about 350px in width, so I’m not worried about overlapping text.
Here is an approach using CSS Flexbox:
It uses an invisible third flex item the same width as the left item.
You need to decide what you want to happen when viewed on small smartphones. I have included flex-wrap: wrap;
so the flex items will automatically wrap on small screens. I have set the height of the third item to zero so it does not take up vertical space when there is wrapping. However when the third item wraps, the centre item will go to the right.
Whatever approach you take, I think you are likely to need to use @media queries to deal with small screens.
In my example the centred text is centred in the viewport which seemed to be exactly what you are asking for. Thats why the top 2 rows are there just to compare it works as expected.
@Archibald The layout would have to be different depending on the device, but this flexbox approach looks great, thanks.
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.