0

I'm trying to get a div with a button next to a parent div. Like this:

____________
|relative  |
|          |
|          |
|          |_______
|          | fixed |
|          |_______|
|          |
|          |
|__________|

The fixed div has to be fixed during scrolling but at all time next to the parent and not under or above its parent.

How can I accomplish this?

TylerH
  • 20,799
  • 66
  • 75
  • 101
MmynameStackflow
  • 1,251
  • 3
  • 19
  • 39
  • Do you have anything you've tried previously? If so - can you post your code. – micp Mar 15 '13 at 10:46
  • "fixed" means it never moves if u scroll the page "absolute" means, it moves when the page scrolls but adding elements will not trouble its position What do u want ?? – madhairsilence Mar 15 '13 at 10:47

3 Answers3

3

Your main problem is that the element with position: fixed is always relative to the body. It behaves differently from elements with position: absolute, which is relative to parent element with position: relative declared.

So the main problem is, that if you set left to the fixed element, it sticks to left edge of body element, even if it's parent is positioned relative. But you could use a trick, and skip left declaration for fixed element.

.main {
    /*just for visualisation*/
    width: 300px;
    height: 1500px;
    background: #ccc;
}
.main, .fake-wrapper {
    float: left;
}
.fixed {
    position: fixed;
    top: 50%;
}
<div class="main">
<!-- your content -->
</div>
<div class="fake-wrapper">
    <div class="fixed">
        <a href="/">click!</a>
    </div>
</div>

Here's a JSFiddle example

TylerH
  • 20,799
  • 66
  • 75
  • 101
nd_macias
  • 784
  • 1
  • 5
  • 13
2

Use position:fixed for the second div

HTML

<div class="main">
    zx
</div>
<div class="fix">
    <button>Click</button>
</div>

CSS

html, body{
    height:100%;
    margin:0
}
.main{
    height:100%;
    width:50%;
    background:grey;
}
.fix{
     position:fixed;
     top:50%;
     border:red solid 2px;
     background:yellow;
     left:50%
}

DEMO

Sowmya
  • 26,684
  • 21
  • 96
  • 136
0

you're looking for position: absolute, not fixed -- if your parent has the class parent and the button has the class button, what you need is similar to (assuming button has a fixed width of 100px for this):

.parent { position: relative; }
.button { position: absolute; top: 45%; right: -100px; }

here's an example fiddle (added some width/heights to demonstrate, these should come from your content instead) http://jsfiddle.net/WpnP4/

Edit: just realized the question is not 100% clear -- I assumed you wanted the button to be next to a specific element and scroll with the screen. Use position:fixed if you want the button element to stay fixed in the screen.

Nick Andriopoulos
  • 10,313
  • 6
  • 32
  • 56