开发者

css float:left with position left

Why does this not work? I have assigned a bunch of divs with float:left and want to set the position of the first element's position and then have all of the siblings position 开发者_C百科update with it.

For example I set the first element's css left:50px. I was expecting that the siblings would all shift as well but they do not, they stay in their position relative to the parent.

<style type="text/css">
    .wrap {margin:10px; width:auto; height:70px; background:#ccc; position:relative;}
    .floater {width:50px; height:50px; float:left; background:blue; margin:10px 0px 0px 10px; position:relative; left:10px;}
</style>

<div class="wrap">
    <div class="floater" style="left:50px; background:red"></div>
    <div class="floater"></div>
    <div class="floater"></div>
    <div class="floater"></div>                             
</div>

I noticed that if I use margin-left then I get the behavior that I want but I do NOT want to use margin-left because I need to query the current position of the divs from time to time.

Any thoughts on how to achieve what I want? Thanks.

Jacob


This is the correct rendering for left -- the left property is intended for use with position, to adjust the positioning of a given element without affecting anything else around it.

Typically you'd use left, right, top and bottom to create a fixed layout for a group of elements. Each of them would be position:relative; (or absolute or fixed) and have their own positioning which would place them relative to their parent element, not relative to each other.

This is obviously quite at odds with the concept of float, where elements are very much positioned relative to each other.

Two solutions come to mind which will do what you want:

1) put padding-left:50px; on the container wrap div element instead of left:50px; on the floated element as you have it.

2) use display:inline-block; instead of float:left;. This tends to make layout work easier than with floats. I prefer the inline-block solution, because I find floats to be quite painful to work with sometimes, especially when I want to fine-tune my layout.

See my JSFiddle examples: http://jsfiddle.net/xgKBc/


You can either give every floater a relative position of 50px on the left side. Or you can add a padding-left of 50px to the wrapper.

See demo fiddle with both examples.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜