3 Replies Latest reply: Feb 7, 2013 2:06 PM by mytaxsite.co.uk RSS

    Can a div auto-detect the width of its contents?

    jyeager11 Community Member

      By default, a div's width will extend as far as its container allows (100%) and we can restrict this by specifying width values. But I'm not looking to do either one. Instead, I'd like to know if there's a way to make a div adopt the width value of its contents dynamically?

       

       

      In other words, wrap tightly around its contents, instead of expanding to fill whatever space allows.

       

      <div>
        <img src="image.jpg">
      </div>

       

      Where image.jpg is 200px wide and so is the div that's containing it.

        • 1. Re: Can a div auto-detect the width of its contents?
          Nancy O. CommunityMVP

          #divName {width:auto;}

           

           

          Nancy O.

          • 2. Re: Can a div auto-detect the width of its contents?
            Jon Fritz II CommunityMVP

            If you change the display of the containing <div> to inline-block it will only be as wide as it's content.

             

            This code puts a 5px space between the content and the <div>. The <div> itself ends up as wide as the content plus the padding...

             

            <style type="text/css">

            #holder {

                display:inline-block;

                border:1px solid black;

                padding:5px;

            }

            </style>

            </head>

             

            <body>

                 <div id="holder">

                      <img src="image.jpg" alt="#" />

                 </div>

            </body>

             

            I think that's what you're looking for.

            • 3. Re: Can a div auto-detect the width of its contents?
              mytaxsite.co.uk CommunityMVP

              jyeager11 wrote:

               

              By default, a div's width will extend as far as its container allows (100%) and we can restrict this by specifying width values. But I'm not looking to do either one. Instead, I'd like to know if there's a way to make a div adopt the width value of its contents dynamically?

               

               

               

              Where image.jpg is 200px wide and so is the div that's containing it.

               

              Yes you can do it.  You need to float the DIVs either left or right.  The process of floating the div shrinks the div to fit the contents.  Try it and let us know if this works in your case.

               

              Good luck.