【问题标题】:Cannot align divs with % widths or heights properly?无法将 div 与 % 宽度或高度正确对齐?
【发布时间】:2015-05-09 13:45:08
【问题描述】:

我在正确对齐页面上的元素时遇到问题。我这里有一个活生生的例子..http://newbapps.com/8ball/

div 'answer' 应该覆盖在 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>

【问题讨论】:

    标签: javascript html css alignment


    【解决方案1】:

    您可以将图像 (#ball) 和答案 (#answer) 放在容器 div 中,给它 position: relative;,然后使用 position: absolute; 定位元素。

    【讨论】:

    • 我添加了一个容器,将其位置设置为相对,并将#ball 和#answer 设置为绝对,但仍然遇到问题。
    • 玩了一会儿,我发现你的建议其实就是答案。感谢您为我指明正确的方向。
    猜你喜欢
    • 2018-12-21
    • 1970-01-01
    • 2012-07-07
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 2014-05-05
    • 1970-01-01
    • 2020-05-27
    相关资源
    最近更新 更多