Dynamic “Top” align an item

Happy New Year!

The other day I’m sitting there working on an awesome project (like I always do) and one of the requirement was to have an element on the page align to the top of another element. Well…im my case, the requirement was to have Element-A to float on top of the Element-B and aligned in the top right of Element-B…regardless of Element-Bs dimensions.

Not so easy when you have to consider a few things

  • Screen resolution changes the overall Element-B size
  • Element-As size is inconsistent
  • The page size may change

Here is a preview of what im trying to do.

I need the blue box to float to the top right of the red box, regardless of the red boxes dimensions.

 I knew I couldn’t accomplish this with using just CSS. So I relied on jQuery to get me to where i needed to be.

In jQuery, i basically needed to

  1.  Find the height of Element-B (red box in sample image)
  2. Position Element-B (blue box in sample image) to top of Element-B by injecting CSS with jQuery

There are a few things that need to be set up to get the results that I needed. First I had to have the “position” in CSS set to “relative” of Element -A. To get my Element-A to shove over to the right, set the “float” in CSS to “right”.

The Done:

.text_wrapper
{
float:right;
position:relative;
}
 
var imgHeight = $(‘.slider’).height();
$(‘.slider_caption’).css({‘top’:-imgHeight });
 
<div id=”element”>
<img id=”img” src=”” alt=”” />
<div id=”text_wrapper”>
<span id=”title”>Sample title</span>
<span id=”caption”>Sample caption</span>
</div>
</div>

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.