Vertically aligning block element to image?

前端 未结 1 903
一生所求
一生所求 2021-01-17 05:09

I\'m looking for a way to vertically align a block element to an image. On my site this image would dynamically change in height and width so I\'d need the vertical alignmen

1条回答
  •  日久生厌
    2021-01-17 05:41

    The trick is to add a couple layers of wrapper-divs. The first layer is set to white-space: nowrap and max-width:50% which means that the elements inside can't wrap, and are constrained to 50% of the width of the parent.

    Then you set the white space back to normal, and make the second layer display:inline-block so that these divs have to play by text alignment rules. Then you set both of them to vertical-align:middle; Just one won't work because vertical align is relative to the baseline of the text, not the containing block element.

    So in this way we have constrained ourselves to one line of "text", composed of two div elements both aligned such their middle is at the text baseline, and ensured that their size must be no more than 50% of the parent container.

    EDIT: I discovered after little more playing that you need to add some max-width:100% to keep the image from pushing the text out the right hand side.

    EDIT 2: I should have mentioned that this requires IE-8 standards mode, added meta-equiv to tell IE-8 to behave itself, but giving a proper doctype or sending an http response header can achieve the same thing google IE8 standards mode for all that stuff.

      
        
        Test  
        
        
        
        
      
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

    0 讨论(0)
提交回复
热议问题