垂直居中未知高度

时间:2013-03-13 17:13:38

标签: css center vertical-alignment centering

我正在尝试将图像垂直居中在没有固定/指定高度的DIV中。我已经尝试在Centering in the unknown article on CSS Tricks上构建,但要实现这一点,您需要指定高度。相反欺骗文章标题。

这是我的JS小提琴: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; }

1 个答案:

答案 0 :(得分:3)

你不能使用伪元素技术的原因是因为你没有足够的祖先元素,它们是#you-and-us元素高度的100%。

如果您丢弃浮点数并对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; }
相关问题