How do I keep a DIV from expanding to take up all available width?

前端 未结 5 694
礼貌的吻别
礼貌的吻别 2021-02-18 12:54

In the following HTML, I\'d like the frame around the image to be snug -- not to stretch out and take up all the available width in the parent container. I know there are a coup

相关标签:
5条回答
  • 2021-02-18 13:26

    The beige rectangle is so wide because you have display: block on the span, turning an inline element into a block element. A block element is supposed to take up all available width, an inline element does not. Try removing the display: block from the css.

    0 讨论(0)
  • 2021-02-18 13:27

    The right way is to use:

    .pictureframe {
        display: inline-block;
    }
    

    Edit: Floating the element also produces the same effect, this is because floating elements use the same shrink-to-fit algorithm for determining the width.

    0 讨论(0)
  • 2021-02-18 13:38

    Yes display:inline-block is your friend. Also have a look at: display:-moz-inline-block and display:-moz-inline-box.

    0 讨论(0)
  • 2021-02-18 13:45

    The only way I've been able to do picture frames reliably across browsers is to set the width dynamically. Here is an example using jQuery:

    $(window).load(function(){
      $('img').wrap('<div class="pictureFrame"></div>');
      $('div.pictureFrame').each(function(i) {
        $(this).width($('*:first', this).width());
      });
    });
    

    This will work even if you don't know the image dimensions ahead of time, because it waits for the images to load (note we're using $(window).load rather than the more common $(document).ready) before adding the picture frame. It's a bit ugly, but it works.

    Here is the pictureFrame CSS for this example:

    .pictureFrame {
      background-color:#FFFFFF;
      border:1px solid #CCCCCC;
      line-height:0;
      padding:5px;
    }
    

    I'd love to see a reliable, cross-browser, CSS-only solution to this problem. This solution is something I came up with for a past project after much frustration trying to get it working with only CSS and HTML.

    0 讨论(0)
  • 2021-02-18 13:46

    Adding "float:left" to the span.pictureFrame selector fixes the problem as that's what "float:left" does :) Apart from everything else floating an element to the left will make it occupy only the space required by its contents. Any following block elements (the "p" for example) will float around the "floated" element. If you "clear" the float of the "p" it would follow the normal document flow thus going below span.pictureFrame. In fact you need "clear:left" as the element has been "float:left"-ed. For a more formal explanation you can check the CSS spec although it is beyond most people's comprehension.

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