Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Centering div`s using jquery

Hi everybody! (imagine voice of Dr. Nick from Simpsons)

I am facing a bit of a dilemma here. In my code Im using a few different divs and I want to center them all in the browsers window center. To do that I`m using this bit of jquery:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

    <script type="text/javascript"> 


      $(window).resize(adjustLayout).resize(); 
      $(document).ready(function(){
          adjustLayout();
      })

      function adjustLayout(){
          $('#some_div1, #some_div2, #some_div3').css({
              position:'absolute',
              left: ($(window).width() - $('#some_div1').outerWidth())/2,
              top: ($(window).height() - $('#some_div1').outerHeight())/2
          });

      }
</script>

When the page loads, div`s are being centered vertically (yay!) but not horizontally - until the page is resized manually. What could be the fix?

Thanks!

Dave McFarland
Dave McFarland
Treehouse Teacher

Hi Aidas,

For the future, to put HTML/CSS/JavaScript in a forum post:

  1. hit return to create a new line and type three back tick characters ```

  2. hit return to create another new line and paste your HTML

  3. hit return and add three more back tick characters: ``` The back tick character isn't the same as the single quote -- ' -- mark; the back tick is located on the same key as the ~ on most keyboards.

Also to add correct color highlighting add the name of the language after the back ticks like this: ```CSS. Here's what CSS should look like in a forum post:

#gallery li {
  float: left;
  width: 45%;
}

Thanks, Dave - now I get it! Updated the entry.

Can you post your html and css as well? Or consider putting this on codepen.

1 Answer

Yeah, it works if the div`s are selected statically in the css first, forgot that. However, if anybody knows more elegant solution. please comment

#some_div{
position: absolute;
}