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

前端 未结 5 707
礼貌的吻别
礼貌的吻别 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: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.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.

提交回复
热议问题