treehouse : what would you like to learn today?
Web Design Web Development iOS Development

CSS Positioning

  • I am totally new to CSS, but I am learning. I was searching how to center on CSS but you can only align top or left, right, or set a value like -50px.
    How can I make an image to center? Imagine there is an image in a screenshot.
    http://www.ipix.lt/desc/49464521
  • You center images using text-align: center; and you center elements such as divs using margin: auto;
  • text-align: center; will be form left to right center, I need center from top to bottom.

    .post .inner {
    padding: 22px 14px 14px;
    margin-bottom:14px;


  • Vertical centering is quite difficult to properly accomplish.

    Looking at the screenshot you posted I'm not really sure what you're trying to achieve.
  • OK, I am making an image archive type blog. It is made out of dynamic tiles. The problem is that images have different aspect ratio, so to align them well I have to make fixed size of each tile. If image is wide it leaves a big white gap. Centering it would make that space smaller, since it would be shared on top and bottom. I am attaching a better screenshot.
    http://www.ipix.lt/desc/31035498/
  • What you're saying is that you want each image to be vertically centered. What is your code for your images?

    Usually it's something like this
    background: url(/images/image.png) center center no-repeat;
  • Yes, exactly!
    But the size of each tile is variable and there is a a lot of code.
    (I am editing code on tumblr, if this makes any difference)
    What should I change?

    .post {
    background: {color:Post Background};
    display: block;
    margin: 14px;
    float: left;
    text-align: center;
    position: relative;
    overflow: hidden;
    border-radius: 8px;
    -moz-border-radius: 8px;
    -webkit-border-radius: 8px;
    -webkit-box-shadow: 0px 5px 40px rgba(0,0,0,0.75);
    }
    .post .inner {
    padding: 22px 14px 14px;
    margin-bottom:14px;
    }

    .post.large {
    height: 708px;
    width: 528px;
    }
    .post.small {
    height: 436px;
    width: 328px;
    }
    ol#posts.permalinkpage .post {height:auto;}
    .post.large .photo img {
    margin-bottom: 10px;
    }
    .post.small .photo img {
    margin-bottom: 10px;
    width: 300px;

  • Try using vertical-align: middle on the elements you want to center vertically. Notice that the container should have a line-height equal to its height for this trick to work. vertical-align does not work for block elements so you can't center both your image and those buttons. I suggest you to keep those buttons on top and below your header while you center your image using vertical-align. here's an example I made: http://jsbin.com/omapi4/3/edit (click preview to see the results)

    Another solution would be using javascript =)