CSS: Inline element stretch to fill available horizontal space of container

前端 未结 3 1360
情书的邮戳
情书的邮戳 2021-02-05 07:16

For example I have a 200px div containing three buttons, the text is only minimal so the buttons don\'t fill the horizontal space available. Is it possible to..

3条回答
  •  再見小時候
    2021-02-05 08:15

    I've realised that the real issue is buttons won't stretch until you give them an explicit width (ie, width:100%). You still need the table-cells though to constrain that 100% to a 'what will fit' model. You could just set 33% on each button but that won't work if your buttons are being added dynamically (unless you calculate the percentages on the server).

    METHOD 1 (doesn't work): Buttons don't expand to fit the row (ie, display:table-cell appears to be ignored).

    For IE prior to IE8 you'll need to feed a real table or a compatibility script like IE8-js. The basic concept is easy enough though:

    
    for (el in getElementsByTagName('button')) {
        if el.style.find('display:table-cell') {
            el.innerHTML = ''
        }
    }
    
    
    

    METHOD 2 (works): Hmmm.. Well for whatever reason the display:table-cell style does not work on button elements. I was able to do it with some extra markup though.

    I admit it ain't pretty but it will ensure all of the horizontal space is filled. It can be cleaned up a bit by using classes like in this demo I put together. Still, when combined with IE's shortcomings this is probably a case where I'd say ignore the purists and just use a table:

    
    
    

提交回复
热议问题