1

Well I wish to show sidebar elements aligned with respect to the main content mentioned Id's instead of just stacking up one after the another in the sidebar. That is I want the sidebar elements with mentioned Id's to align with certain id tags mentioned in the main post content. Here is what the basic structure should look like in the image: http://bit.ly/1tbOHEY align content with sidebar along the targeted id's

I also want the sidebar element to get aligned with the content when the sidebar disappears in the mobile platform using media queries, so that these elements don't disappear with the sidebar in the mobile platforms.

I can align stuff but I don't know how to do this type of targeted aligning with respect to id's or classes. An example will be very helpful (jsfiddle). Many thanks in advance :)

Geniusknight
  • 629
  • 1
  • 7
  • 22

1 Answers1

0

It's a bit of an old question, yet I had been looking for a solution to this topic for a few hours. I could find mine, and I based it on the original fiddle. I am sure it could be done better and cleaner. After all I'm still a noob.

I added the required JS:

var el_from = document.getElementById("alignwithme1")
var rect = el_from.getBoundingClientRect();
var el_to = document.getElementById("se1")
new_style = "position: absolute; width:270px; top: " + rect.top + "px;"
/* console.log(new_style)
displays: position: absolute; width:270px; top: 55px; */
el_to.style= new_style;

el_from = document.getElementById("alignwithme2")
rect = el_from.getBoundingClientRect();
el_to = document.getElementById("se2")
new_style = "position: absolute; width:270px; top: " + rect.top + "px;"
/* console.log(new_style)
displays: position: absolute; width:270px; top: 278px; */
el_to.style= new_style;

Here's the fiddle.

It is based on this popular solution to finding the position of an item in the DOM, which suggests using getBoundingClientRect(). Then I calculate a new positioning style (1) for the element that needs to be associated with the original, and apply it.

I could not yet find how to make two details perfect, i.e.:

  1. adapt the width to your required size, because by applying the position: absolute the width: auto does not seem to work anymore
  2. There seems to be a slight mismatch in the alignment, but I don't know where it comes from.
Giampaolo Ferradini
  • 529
  • 1
  • 6
  • 17