css - 垂直居中未知高度

标签 css center vertical-alignment centering

我试图将图像垂直居中在没有固定/指定高度的 DIV 中。我尝试过在 Centering in the unknown article on CSS Tricks 上进行构建但要使其发挥作用,您需要指定高度。而是欺骗性的文章标题。

这是我的 JS fiddle :http://jsfiddle.net/6J2WA/

这就是我想要的(图片):http://cl.ly/image/1k0h262c2c3s

CSS

/* This parent can be any width and height */
.block {
  text-align: center;
}

/* The ghost, nudged to maintain perfect centering */
.block:before {
  content: '';
  display: inline-block;
   height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}

/* The element to be centered, can
also be of any width and height */ 
.centered {
  display: inline-block;
  vertical-align: middle;
}


.inner {
max-width: 960px;
margin: 0 auto;
overflow: hidden;
    background: #ef4;
}

.c-3 {  
width: 29.3%;
float: left;
margin-left: 6%;
    background: #e4f;
}

#you-and-us .c-3 { width: 33.5%; }
#you-and-us .c-3:first-child { text-align: right; margin: 0; }
#you-and-us .c-3:nth-child(2) { width: 21%; text-align: center; position: relative; }

最佳答案

无法使用伪元素技术的原因是因为您没有足够的祖先元素,其高度为 #you-and-us 的 100%元素。

如果你扔掉 float 并使用display: table-cell,你可以简化整个事情。为您.c-3元素。

http://jsfiddle.net/6J2WA/5/

/* This parent can be any width and height */
.block {
    text-align: center;
}

.inner {
    max-width: 960px;
    margin: 0 auto;
    overflow: hidden;
    background: #ef4;
}

.c-3 {  
    display: table-cell;
    background: #e4f;
}

#you-and-us .c-3 { width: 33.5%; }
#you-and-us .c-3:first-child { text-align: right; }
#you-and-us .c-3:nth-child(2) { width: 21%; text-align: center; position: relative; background: yellow; vertical-align: middle; }

关于css - 垂直居中未知高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15392002/

相关文章:

css - 在固定大小的 div 中垂直对齐居中图像

css - 将 div 应用为鼠标悬停淡入 100% 宽度标题的简单未膨胀方法

html - CSS/HTML 内联显示表格,直到它们超过父 div 的宽度?

css - 如何在 font awesome icon fa fa-circle 上创建水平居中线?

html - 垂直对齐不是像素完美的

html - 多行垂直对齐

javascript - CanvasJS 图表不显示

html - 响应图像锚定在其容器 div 的顶部

jquery - 导航悬停不起作用

html - 图像在 Wordpress 中居中对齐