CSS: display:inline-block and positioning:absolute

后端 未结 3 567
广开言路
广开言路 2020-11-28 07:51

Please consider the following code:



    

        
3条回答
  •  有刺的猬
    2020-11-28 08:52

    When you use position:absolute;, the element is taken out of the normal page flow. Therefore it no longer affects the layout of its container element. So the container element does not take into account its height, so if there's nothing else to set the height, then the container will be zero height.

    Additionally, setting display:inline-block; does not make any sense for an element that is position:absolute;. Again, this is because absolute positioning takes the element out of the page flow. This is at odds with inline-block, which only exists to affect how the element fits into the page flow. All elements that are position:absolute; are automatically treated as display:block, since that's the only logical display mode for absolute positioning.

    If you need absolute positioning, then the only solution to your height problem is to set the height of the container box.

    However, I suspect that you could do without the absolute positioning.

    It looks like what you're trying to do is position the second in each block to a fixed position in the block, so that they line up.

    This is a classic CSS problem. In the "bad-old-days", web designers would have done it using a table, with fixed widths on the table cells. This obviously isn't the answer for today's web designers, but it is something that causes a lot of questions.

    There are a number of ways to do it using CSS.

    The easiest is to set both the elements to display:inline-block;, and give them both a fixed width.

    eg:

    some text some text

    with the following CSS:

    .section span  {display:inline-block;}
    .element-left  {width:200px;}
    .element-right {width:150px;}
    

    [EDIT]after question has been updated

    Here's how I would achieve what you're asking now:

    some text some text
    some text some text
    some text some text

    with the following CSS:

    .section span  {display:inline-block;}
    .element-left  {width:200px;}
    .indent-1 {padding:10px;}
    .indent-2 {padding:20px;}
    .element-right {width:150px;}
    

    A small amount of extra markup, but it does achieve the effect you want.

提交回复
热议问题