简体   繁体   中英

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?

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;
}

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 div s 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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM