html - 尝试垂直对齐段落元素

标签 html css

我有一些简单的CSS,旨在在其父div的中间(垂直)显示一个段落元素。

我的问题:段落元素未垂直对齐,始终位于顶部。此解决方案仅适用于Safari(特别是iPad的Safari版本)。

您知道如何使我的段落元素垂直对齐中间吗?

<html>
<head>

    <style type="text/css">
    <!--
        .ButtonBox { 
            cursor: pointer; 
            vertical-align: middle;
            text-align: center;
            background-color: blue;
            height: 200px;
        }

        .buttonBoxContainer { 
            cursor: pointer;
        }
    -->
    </style>
</head>
<body>

    <div class="ButtonBox">
        <p class="buttonBoxContainer">Press Me</p>
    </div>

</body>
</html>

最佳答案

如果框始终具有静态高度,则可以使用line-height将段落元素居中,如here所示。

如果不是静态的,最好的解决方案(以我的经验)是使用javascript。

<html>
<head>
    <style>

        .ButtonBox { 
            cursor: pointer; 
            vertical-align: middle;
            text-align: center;
            background-color: blue;
            height: 200px;
            color: #fff;
        }

        .buttonBoxContainer { 
            cursor: pointer;
            line-height: 200px;
        }
    </style>
</head>
<body>

    <div class="ButtonBox">
        <p class="buttonBoxContainer">Press Me</p>
    </div>

</body>
</html>

关于html - 尝试垂直对齐段落元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8047124/

相关文章:

javascript - 警报后背景变化

html - LoC 方面的 CSS 优化

javascript - 如何链接到标题并在 JavaScript 中单击链接时触发单击事件?

javascript - 使用 Scrollmagic 补间文本框的不透明度

调整窗口大小时,CSS 不会立即应用。它只适用于滚动

javascript - 使用 url 参数填充 div,但前提是在使用 settimeout 后另一个 span 为空

javascript - 是否可以在图像的特定点上设置事件?

javascript - 为什么javascript按下回车按钮没有功能?

html - 居中对齐 div 内容的正确方法

css - iPhone 6 的响应式设计?