Search code examples
javascriptjquerycsscss-floatliquid-layout

Find the width of a left floated list and apply to wrapper div to center it using css - jQuery?


I wish to center a ul in a div that is the left column of a liquid layout. To do so I need to set the width of a div that I've used to wrap the ul. Note: the list items (and content) are retrieved from a database using php.

I'm interested in your suggestions on how to do this using jquery.

Consider the below markup:

<div id="wrapper">

   <div id="left-column">
     <div id="list-wrap">
       <ul>
        <li>Dynamic content 1</li>
        <li>Dynamic content 2</li>
        <li>Dynamic content 3</li>
        <li>Dynamic content 4</li>
       </ul>
      </div><!--/list-wrap-->
   </div><!--/left-column-->

   <div id="right-column">
     Content
   </div><!--/right-column-->

   <div style="clear: both;"></div>

   </div><!--/wrapper-->

Using this css:

#wrapper {}
#left-column { float: left; width: 50%; }
#right-column { float: right; width: 50%; }
#list-wrap { margin: 0 auto 0 auto; padding: 40px; }
#list-wrap ul { list-style-type: none; }
#list-wrap ul li { float: left: width 160px; height: 160px; margin: 20px; }

I'm not too clever when it comes to javascript but I'm thinking the solution would entail something like this:

  1. Find the width of the usable content area of #left-column.
  2. Work out how many li's would fit into that width (taking into account the margin and padding of #list-wrap).
  3. Round off the figure to nearest 200px (160px width + 2x20px margins)?
  4. Apply the width to #list-wrap.

Here is something I have used before that meets SOME of the criteria to get started:

   var menuWidth = 0;
   $(".menu > ul > li > a").each(function(i) {
     menuWidth += $(this).outerWidth(true);
     });
    $(".menu").css("width", menuWidth);

Thanks in advance for your help,

Niels


Solution

  • You dont need js to do a css job!

    consider this style:

    #wrapper {}
    #left-column { float: left; width: 50%; }
    #right-column { float: right; width: 50%; }
    #list-wrap { margin: 0 auto 0 auto; padding: 40px; }
    #list-wrap ul { list-style-type: none; text-align: center; }
    #list-wrap ul li { width: 160px; height: 160px; margin: 20px; display: inline-block; }
    

    Get rid of float: left; for the li items and add a display: inline-block;

    Finally, add text-align: center; to the UL to make them centered

    I hope this is what you were lookin for.