Search code examples
htmlcsspositioncss-positionvertical-alignment

Keep relatively positioned child within parent block max-top equivalent needed


There is a html code https://jsfiddle.net/1t68bfex/

button {
  position: relative;
  top: 100px;
  left: 150px;
  max-top: 10px;
}

.third-party-block {
  //display: none;
}
<div style="border:1px solid red;">
  <button>
       The text from the left is beautiful
      </button>
  <div class="third-party-block">
    <p>
      some text comes here
    </p>
    <p>
      some text comes here
    </p>
    <p>
      some text comes here
    </p>
    <p>
      some text comes here
    </p>
  </div>
</div>

The problem here is the third-party-block is dynamic and if it is not displayed, the button should stay near the top. The top:100px should be changed if the height of the parent is too short.

So, I'm looking at something like max-width equivalent for width, but the same for my situation. Pure CSS solution is needed.


Solution

  • You can consider the use of flexbox to achieve this:

    .container {
      border: 1px solid red;
      display: flex;
    }
    
    button {
      margin-top:10px;
      align-self:flex-end;
    }
    .button {
      order: 1;
      max-height:100px;
      display:flex;
    }
    <div class="container">
      <div class="button"><button>
       The text from the left is beautiful
      </button></div>
      <div class="third-party-block">
        <p>
          some text comes here
        </p>
        <p>
          some text comes here
        </p>
        <p>
          some text comes here
        </p>
        <p>
          some text comes here
        </p>
      </div>
    </div>
    <div class="container">
      <div class="button"><button>
       The text from the left is beautiful
      </button></div>
      <div class="third-party-block">
        <p>
          some text comes here
        </p>
        <p>
          some text comes here
        </p>
        <p>
          some text comes here
        </p>
        <p>
          some text comes here
        </p>
            <p>
          some text comes here
        </p>
        <p>
          some text comes here
        </p>
      </div>
    </div>
    <div class="container">
      <div class="button"><button>
       The text from the left is beautiful
      </button></div>
      <div class="third-party-block">
        <p>
          some text comes here
        </p>
        <p>
          some text comes here
        </p>
      </div>
    </div>
    <div class="container">
      <div class="button"><button>
       The text from the left is beautiful
      </button></div>
      <div class="third-party-block">
        <p>
          some text comes here
        </p>
      </div>
    </div>