css - float div的内容垂直居中

标签 css css-float css-position vertical-alignment

如何使 float div 的内容真正居中(我不知道哪个高度)?

有非常简单的 HTML 和 CSS(参见这个 fiddle :http://jsfiddle.net/DeH6E/1/)

<div class="floating">
    This should be in the middle
</div>
​
.floating {
    height: 100px;
    float: left;
    border: 1px solid red;
    vertical-align: middle;
}   ​

如何让“This should be in the middle”这句话真正出现在中间(垂直居中)? vertical-align: middle 似乎不起作用。我试过 display: table-cell 也没有用。解决此问题的最佳方法是什么?我想避免插入任何其他 HTML 标记,只需通过 CSS 即可。

(说明一下:我不知道容器的实际高度,100px只是为了举例)

编辑: 我希望您能理解我的意思,所以...在设计网页时,我总是遵循 HTML 保存内容而 CSS 负责视觉样式的规则。我从不将它们混在一起,也从不使用一个来启用另一个。在这种情况下,我也想坚持这条规则。我不想仅为 CSS 插入 HTML 元素。

最佳答案

其他人是对的,you need to nest two DOM elements这为您提供了更多控制居中的选项。这是代码:

.floating {
  display: table;
  float: right;
  height: 200px;
  width: 400px;
  border: 1px solid red;
}
.floating p {
  display: table-cell; 
  vertical-align: middle; 
  text-align: center;
}
<div class="floating">
    <p>This is the proper way that validates and breaks across multiple
    lines, if the text is longer than just a few words and still
    should be vertically centered. Here, it's also horizontally
    centered for added joy.</p>
</div>

关于css - float div的内容垂直居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12168145/

相关文章:

jquery - 在 jquery 轮播上添加一个 div 层。艰难的

html - 将 div 置于文本之上

html - 显示器上的相对位置 :table-row

jquery - 使用 CSS 导航翻转并应用 jQuery

html - 导航栏 mask

html - .tooltip 元素中的彩色 CSS 内容

CSS:让新行在上面,而不是下面

Css float 与边距

css - 将选项卡调整为与 Materialize.css 中最高选项卡的高度相同

ios - iOS 位置固定元素的滚动问题