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
aidasvilnius
2,281 PointsCentering 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!
aidasvilnius
2,281 PointsThanks, Dave - now I get it! Updated the entry.
Jason Anello
Courses Plus Student 94,610 PointsCan you post your html and css as well? Or consider putting this on codepen.
1 Answer
aidasvilnius
2,281 PointsYeah, 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;
}
Dave McFarland
Treehouse TeacherDave McFarland
Treehouse TeacherHi Aidas,
For the future, to put HTML/CSS/JavaScript in a forum post:
hit return to create a new line and type three back tick characters ```
hit return to create another new line and paste your HTML
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: