In CSS how can I make an element with "position: absolute" align left but also be contained right?

44 Views Asked by At

The goal is make the absolute-position element align left (achieved by default) but then also supersede the alignment to not extend out the right of .row.

  • In Summary: need to achieve a scaling solution so as the page grows [it aligns left] and shrinks [it aligns right].

<div style="display: flex; position: relative; padding: 10px; background: deepskyblue; max-width: 350px">
  .row
  <div style="width: 150px">
    .col
  </div>
  <div style="position: relative;  padding: 10px; background: blueviolet; width: 150px">
    .col
    <label for="date">
      <b>
        Pick Date
      </b>
    </label>
    <div id="date_picker_listener" style="position: static; width: 100%; background: green">
      #date_picker_listener
      <input id="date" type="text" placeholder="mm/dd/yyyy">
      <div style="position: absolute; width: 250px; height: 50px; background: red; left: 0">
        Absolute
      </div>
    </div>
  </div>
</div>

2

There are 2 best solutions below

0
Rio Weber On BEST ANSWER

I got the solution!

<div style="display: flex; position: relative; padding: 10px; background: deepskyblue; max-width: 750px">
  .row
  <div style="width: 150px">
    .col
  </div>
  <div style="position: relative; padding: 10px; background: blueviolet; width: 350px">
    .col
    <label for="date">
      <b>
        Pick Date
      </b>
    </label>
    <div id="date_picker_listener" style="position: relative; width: 100%; background: green">
      #date_picker_listener
      <br>
      <input id="date" type="text" placeholder="mm/dd/yyyy">
      <div style="position: absolute; width: 200px; height: 50px; background: red; right: 0; margin-right: calc(max(0px, ((100% - 200px))))">
        Absolute
      </div>
    </div>
  </div>
</div>

0
Agustin Riquelme On

Try the following:

  1. Set position: relative on the #date_picker_listener div to establish a containing block for absolute positioning.

  2. Add right: auto; to the absolute-positioned div to ensure it doesn't extend out to the right when the page shrinks.

It should look like this

<div style="display: flex; position: relative; padding: 10px; background: deepskyblue; max-width: 350px">
  .row
  <div style="width: 150px">
    .col 
  </div>
  <div style="position: relative; padding: 10px; background: blueviolet; width: 150px">
    .col 
    <label for="date">
      <b>Pick Date</b>
    </label>
    <div id="date_picker_listener" style="position: relative; width: 100%; background: green">
      <!-- #date_picker_listener -->
      <input id="date" type="text" placeholder="mm/dd/yyyy">
      <div style="position: absolute; width: 250px; height: 50px; background: red; left: 0; right: auto;">
        Absolute
      </div>
    </div>
  </div>
</div>