css – Div with both floating element and vertically centered dynamic content inside


That’s a famous problem but still I could not find a solution to it. What I want to achieve is this:

<div>
  <div class="buttons" style="float: right">BUTTONS</div>
  .... random content of any length/size here vertically centered
</div>

Now, to clarify the problem – it would work fine if the content is higher than the floating buttons, but sometimes it’s not – one line of text and tall buttons.

The existing solutions do not work because for example:

  • I need a floating element so I can’t use flex for container
  • The main content should dictate the container height so I cannot make it position: absolute (well, actually both content and floating should dictate the height)
  • I can’t use fixed height

Here are few things that I tried – you can see that it doesn’t really work – text overlaps floating, container size not increased with content, etc. The first one serves as an example that is almost what I need – except that it’s not centered vertically, that’s the missing part.

<div style="display: flex; flex-flow: column">
      <div style=" border: 1px solid red; vertical-align: middle; display: table-cell; width: 300px">
        <div style="float: right; background: green;">Float</div>
        <div>Text Text Text Text Text Text Text Text Text Tex text text text text text text text text </div>
      </div>
    
      <div style="position: relative; border: 1px solid red; vertical-align: middle; display: table-cell; width: 300px">
        <div style="float: right; background: green;">Float<br/>Float<br/>Float</div>
        <div style="position: absolute; top: 50%; left: 0; transform: translate(0, -50%);">TextText Text Text Text Text Text Text Text Text Text Text Text Text T </div>
      </div>
    
      <div style="position: relative; border: 1px solid red; vertical-align: middle; display: table-cell; width: 300px">
        <div style="float: right; background: green;">Float</div>
        <div style="position: absolute; top: 50%; left: 0; transform: translate(0, -50%);">Text Text Text Text Text Text Text Text Text Text Text1 Text 1Text Text Text Text <br/>Text</div>
      </div>
    </div>



Source link

Latest articles

Related articles

Leave a reply

Please enter your comment!
Please enter your name here