How to position absolute inside a div?

后端 未结 4 553
梦如初夏
梦如初夏 2020-12-24 11:49

I\'m having a strange problem positioning a set of divs inside another div. I think it will be best to describe it with an image:

Inside the black (#box) di

4条回答
  •  甜味超标
    2020-12-24 12:20

    One of #a or #b needs to be not position:absolute, so that #box will grow to accommodate it.

    So you can stop #a from being position:absolute, and still position #b over the top of it, like this:

     #box {
            background-color: #000;
            position: relative;     
            padding: 10px;
            width: 220px;
        }
        
        .a {
            width: 210px;
            background-color: #fff;
            padding: 5px;
        }
        
        .b {
            width: 100px; /* So you can see the other one */
            position: absolute;
            top: 10px; left: 10px;
            background-color: red;
            padding: 5px;
        }
        
        #after {
            background-color: yellow;
            padding: 10px;
            width: 220px;
        }
        
    Lorem
    Lorem
    Hello world

    (Note that I've made the widths different, so you can see one behind the other.)

    Edit after Justine's comment: Then your only option is to specify the height of #box. This:

    #box {
        /* ... */
        height: 30px;
    }
    

    works perfectly, assuming the heights of a and b are fixed. Note that you'll need to put IE into standards mode by adding a doctype at the top of your HTML

    
    

    before that works properly.

提交回复
热议问题