Nicekiwi
Nicekiwi

Reputation: 4807

vAlign element in center, but in a horizontal position relative to content

http://jsfiddle.net/DAFHq/1/

<div id="gray-box">
<div id="red-box"></div>
</div>

I need the RED square to be positioned 20px to the right of the gray box with scrolling content in it, while keeping it vertically aligned in the center.

It should remain positioned relative to the gray box while scrolling and when the screen is resized.

Any ideas? The jsFiddle is one I found and modified to show what I need, The vertical align is perfect, but I have no idea howto position it how I need it horizontally.

Maybe something with jQuery?

Upvotes: 0

Views: 88

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337627

Try this:

var positionFoo = function() {
  $('#foo').css({
    'left': $('#bar').offset().left + $('#bar').width() + 20 + 'px',
    'top': ($(window).height() / 2) - ($('#foo').height() / 2)
  });
};

$(window).resize(positionFoo);
positionFoo();

You will also need to add position: fixed; to #Foo.

Updated fiddle

Upvotes: 1

Holger D. Schauf
Holger D. Schauf

Reputation: 147

you need an holder element for the scrolling elements.

<div id="grey-box">
    <div id="red-box"></div>
    <div id="elements-holder"></div>
</div>

.elements-holder {
    overflow: auto;
}

#grey-box {
    position: relative;
}

#red-box {
    position: absolute;
    right: 20px;
    height: 40px;
    width: 40px;
    top: 50%;
    margin-top: -20px; 
}

Upvotes: 1

Related Questions