Is it possible to place one element relative to another dynamic-sized element using only styles?

Is it possible to place one element relative to another specific element using only CSS styles if some of the parameters are dynamic?

I know that I can easily do this with jQuery, but I'm trying to push everything into a stylesheet that I can, rather than relying on javascript.

Here is code that does more or less what I'm trying to execute, although I would like to get rid of javascript and still have the same effect:

http://jsfiddle.net/EaHU7/

Content:

<div id="reference"> Some text - lorem ipsum, or short, shouldn't matter. See CSS </div> <div id="relative"> Relative </div> 

CSS

 div#reference { min-height:200px; /* could be thousands of pixels */ width:500px; padding:1em; border-style:solid; border-width:1px; } div#relative { width:50px; height:50px; padding:1em; background:orangered; border-style:solid; border-left-style:none; border-width:1px; } 

JS:

 var reference = $("div#reference"); var refPos = reference.offset(); var refWidth = reference.outerWidth(); var refHeight = reference.outerHeight(); var relative = $("div#relative"); var relHeight = relative.outerHeight(); relative .css({ "position":"absolute", "left":(refPos.left + refWidth) + "px", "top":(refPos.top + refHeight - relHeight) + "px" }) .show(); 

Screenshot:

screenshot of dynamically positioning div relative to other dynamically sized div

+4
source share
1 answer

Yes. There are many ways to do this. you can do this with absolute positioning by placing an orange square in your div text and set its right value to "-50px" and its lower value to "0px"

  div#reference { position: relative; } div#relative { position: absolute; right: -50px; bottom: 0px; } 

and your HTML:

  <div id="reference"> Some text - lorem ipsum, or short, shouldn't matter. See CSS <div id="relative"> Relative </div> </div> 

Try something like this. The orange square should remain at the bottom and right at any time, regardless of the size of the reference div.

+3
source

Source: https://habr.com/ru/post/1386464/


All Articles