Traffy
Traffy

Reputation: 2861

HTML/CSS - Position 2 blocks in a independant way

I've two elements in my fieldset, each of them placed in a div. What I wanted to do is to choose their position in the fieldset without impacting the position of the other element. Here's what I'm doing :

http://jsfiddle.net/ALUTp/

I though that with the position : absolute, it would be enough but apperently it isn't.

Any idea?

Upvotes: 0

Views: 49

Answers (2)

James Duffy
James Duffy

Reputation: 1387

To use position: absolute, you have to set position: relative on the parent element. Otherwise the absolute positions are in relation to body element.

Fiddle: http://jsfiddle.net/wv9R6/

fieldset {
    position: relative;
    height: 300px;
    width: 90%;
}
#first {
    position: absolute;
    top: 50px;
    right: 30px;
}
#second {
    position: absolute;
    left: 30px;
    bottom: 30px;
}

Upvotes: 3

Joseph Marikle
Joseph Marikle

Reputation: 78540

You can use position:absolute and it will take the elements out of flow like you're wanting, but you have to make a few changes first. First, you need to assign a parent that the position:absolute elements will base their position on (I assume the fieldset). You do this by giving it the attribute position:relative. fixed and absolute work to, but relative doesn't affect the element's position or flow (unless you also add top, right, bottom, or left attributes). It just can't be the default, position:static. Next, the container will collapse (because the divs are out of flow when they are position:absolute), so you have to give your parent container, which is the fieldset, a height or give it other elements that are not out of flow and give it dimension. Lastly, you need to swap your margin attributes for the top, right, bottom, and left attributes, and you're done.

All that put together looks like this: http://jsfiddle.net/swC2w/

fieldset {
    height: 250px;
    position : relative;
}

#first {
    top: 90px;
    position : absolute;

}

#second {
    position : absolute;
    left : 290px;
    bottom : 190px;

}

Upvotes: 1

Related Questions