How exactly does absolute position element behaves inside a static parent

后端 未结 2 1254
既然无缘
既然无缘 2021-01-06 04:06

I ask this question because yesterday I had to style several divs as it\'s shown in this JSFiddle example.

The tricky part for me was to position

2条回答
  •  隐瞒了意图╮
    2021-01-06 04:24

    You did not specify any of top, bottom, left or right for your absolutely positioned element, so it remains in the static position and doesn't go anywhere.

    This happens regardless of whether your element is in another positioned element or not, and is completely by design; see my answer to this question for an explanation from the CSS2.1 spec.

    I see in your fiddle you're trying to float your absolutely-positioned element; that will not work. Once you absolutely position an element, it cannot float:

    The three properties that affect box generation and layout — 'display', 'position', and 'float' — interact as follows:

    1. If 'display' has the value 'none', then 'position' and 'float' do not apply. In this case, the element generates no box.

    2. Otherwise, if 'position' has the value 'absolute' or 'fixed', the box is absolutely positioned, the computed value of 'float' is 'none', and display is set according to the table below. The position of the box will be determined by the 'top', 'right', 'bottom' and 'left' properties and the box's containing block.

    Removing the position: absolute declaration alone will cause your element to reposition itself because it's now floating (it's actually being pushed down by #vertical-menu because there's not enough room), and once you remove the float: left declaration as well, it returns to its usual, static position.

    Note also that when you absolutely position the element it is still taken out of the normal flow. If you tried to add content directly after

    ...
    you'll see that extra content appearing in the same spot instead of being pushed down.

提交回复
热议问题