无法正确对齐%宽度或高度的div?

时间:2015-03-08 08:20:01

标签: javascript html css alignment

我无法正确对齐页面上的元素。我在这里有一个实例。http://newbapps.com/8ball/

div'回答'应该叠加在img'ball'的三角形上。问题是,即使使用不同的窗口大小,我也希望它看起来也能正确居中。如果我使用像素宽度/高度值为我的图像和div,它将更容易完成,但由于我使用百分比我的div'回答'没有正确地居中'球'。请帮忙:(

<html>
<head>
    <style>
        #ball {
            width: auto;
            height: 50%;
            display: block;
            margin: 0 auto;
        }

        #answer {
            width: 5%;
            background-color: red;
            text-align: center;
            position: absolute;
            margin: 0 auto;
            margin-top: 6%;
            left: 0;
            right: 0;
        }

        textarea {
            width: 600px;
            height: 100px;
            display: block;
            margin: 0 auto;
        }

        button {
            width: 600px;
            height: 50px;
            display: block;
            margin: 0 auto;
        }

        h1 {
            font-size: 4.2em;
            text-align: center;
        }

    </style>
</head>
<body>
<h1>Magic 8 Ball</h1>
<p id="answer">Yes.</p>
<img src="ball.png" id="ball">
<textarea></textarea>
<button onclick="getAnswer()">Shake</button>
<script>
    function getAnswer() {
        var answers = ["It is certain.",
                        "It is decidedly so.",
                        "Without a doubt.",
                        "Yes definitely.",
                        "You may rely on it.",
                        "As I see it, yes.",
                        "Most likely.",
                        "Outlook good.",
                        "Yes.",
                        "Signs point to yes.",
                        "Reply hazy try again.",
                        "Ask again later.",
                        "Better not tell you now.",
                        "Cannot predict now.",
                        "Concentrate and ask again.",
                        "Don't count on it.",
                        "My reply is no.",
                        "My sources say no.",
                        "Outlook not so good.",
                        "Very doubtful."]
        var randomAnswer = answers[Math.floor(Math.random() * answers.length)];
        document.getElementById('answer').innerHTML = randomAnswer;

    }
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

您可以将两个图片(#ball)和答案(#answer)放入容器div中,给它position: relative;然后使用{{1}定位元素}}

相关问题