简体   繁体   中英

Vertically aligning an image with CSS

I have written this little game for my kid to play with that every time he hits a key or clicks the mouse that the screen will generate a random colour and letter and display it to him. I have now decided to make it add animal flash cards as well. The problem is I can't seem to get the damned images to vertically align in the div box that's floating in the middle. Any ideas?

Live version minus the animals can be viewed here if you need some idea as to what I'm going on about - http://64-b.it

<html>
  <link rel="stylesheet" type="text/css" href="style.css" />
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
  </script>
  <script type="text/javascript">
    var alphabet = new Array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
    function getNum() {
        return "#" + Math.round(Math.random() * (16777215 - 0) + 0).toString(16);
    }
    function getLetter() {
        var ranNum = Math.round(Math.random() * (101 - 0) + 0);
        if(ranNum < 61){
            return alphabet[ranNum];
        }else{
            return "<img src='images/1.jpg' width='480px' />";
        }
    }

    function doStuff(){
        document.bgColor=getNum();
        document.getElementById('middle').innerHTML=getLetter();
    }

    $(window).on('click touchstart', function(){
        doStuff();
    });

    $(window).keydown(function(){
        doStuff();
    });

  </script>
  <body oncontextmenu="return false">
    <div id="middle">
    </div>
  </body>
</html>

And the CSS:

#middle {
    border-radius: 50px;
    font-weight: 500;
    text-align: center;
    font-family: consolas;
    font-size: 500px;
    border: solid 20px black;
    position: absolute;
    left: 50%;
    top: 50%;
    background-color: #fff;
    z-index: 100;
    height: 590px;
    margin-top: -295px;
    width: 490px;
    margin-left: -245px;
    display: table-cell;
    vertical-align: middle;
}

Instead of display:table-cell; and vertical-align:middle; you can just set a line-height equal to the div's height, that will center text (single-line) and images vertically

What if you set something like this to cheat it:

#middle img {
 position: relative;
 top: 10%;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM