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

CSS

martin maza
martin maza
4,771 Points

Horizontal/Vertical Centering Help? Child Div won't center inside Parent Div

Hi guys,

I've just started creating my about me page, I'm struggling on vertical and horizontal centering text inside my parent div.

Code: http://codepen.io/87maza/pen/yeRzwX

I've used css-tricks as reference, I did the flexbox and fixed height width method but it still won't center.

This was my reference: https://css-tricks.com/centering-css-complete-guide/

Thanks in advance!

3 Answers

Callum King
seal-mask
.a{fill-rule:evenodd;}techdegree
Callum King
Front End Web Development Techdegree Student 4,934 Points

For it to have a percentage based height, itโ€™s parent element, the body, should have a declared height. Then you can use flexbox, to center the child elements.

/* ---- reset ---- */

body {
  margin: 0;
  width: 100%;
  font:normal 75% Arial, Helvetica, sans-serif;
  height: 600px;

}

canvas {
  display: block;
  vertical-align: bottom;
}


#parent {
  width: 100%;
  height: 65%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: navy;
  background-repeat: no-repeat;
  background-size: cover;
}

.child {
  width: 50%;
}

.name {
  text-align: center;
}
Callum King
seal-mask
.a{fill-rule:evenodd;}techdegree
Callum King
Front End Web Development Techdegree Student 4,934 Points

If you removed all your current CSS, and added the code below, it would center all the text?

body {
  text-align: center;
  width: 65%;
  margin: 0 auto;
}
martin maza
martin maza
4,771 Points

Thanks Callum, however, its not necessarily the answer to vertically and horizontally centering the child div.

The parent div is supposed to have a navy background and set to 65% height but something in my CSS is overwriting it. I appreciate the help!