Search code examples
htmlcsscenter

css/html, how to scale and center a logo image


I'm trying to create a typical main menu screen for a game. It's got a logo, centered at the top, and some menu buttons. It will always be shown in landscape layout and it needs to support different resolutions.

here's what I've got so far: http://jsfiddle.net/L3mNT/

My questions are these:

1) Is it possible to center and scale the logo using only DIV? Or is it okay to "resort" to using the img-tag and center-tags? What are the (dis)advantages of a DIV? The DIV logo does scale when I tried adding a height in pixels, like so

.logo{
    ..
    height:120px;
}

but that would have to be updated through javascript in the resize event. I figured it ought to be possible using only css, or am I wrong..?

2) How do I vertically center the menu div, the buttons need to be in the middle of the screen and may not drop off the bottom of the screen. The following didn't work

.menu{
    width:50%;
    height:50%;
    margin:auto auto;
}

Solution

  • The img tag is okay. The center tag is obsolete since about 1867. But you can easily use text-align: center as a style on the parent element of the logo.

    So with a piece of HTML like this:

    <div class="logo"><img src="..."></div>
    

    and a piece of CSS like this:

    .logo {
      text-align: center;
    }
    .logo img {
      width: 50%;
    }
    

    You should have a centered logo of about half the width of the page.

    There is no shame in using the img tag, and in fact, if you want to scale, then it's very convenient to have this. An image will automatically scale its height relatively according to its width. There is no easy way to get the same effect using just a background image.

    Alternatively, you can make the logo a background. But then you'll have to specify the height of the container, because it doesn't have any content at all and will otherwise collapse:

    .logo {
        text-align: center;
        background-color: red;
        background-image: url('http://jsfiddle.net/img/logo.png');
        background-size: contain;
        background-position: 50% 0;
        background-repeat: no-repeat;
        height: 100px;
    }
    

    http://jsfiddle.net/cwj2b/