2012-03-22 100 views
2

这里是我的标记:垂直对齐,没有高度知

<div id="container"> 
    <img id="image" src="image.jpg" /> 
    <div id="contents">Contents</div> 
</div> 

#container高度等于#image高度。 所有高度都是动态的(它们在窗口大小调整时发生变化)。 无法通过背景属性设置图像。

我怎样才能有图像上的内容和垂直居中在#container

+0

为什么不能将图像设置为背景?你没有得到它的工作,或有这种选择的特定原因? – justanotherhobbyist 2012-03-22 12:59:02

+0

我确定通过设置背景图像很容易做到这一点。然而,这是不可接受的 - 图像是一个后缩略图,在搜索引擎优化中相当重要 – Sergey 2012-03-22 16:43:33

+0

我假设高度不知道,宽度也不知道? – Andrew 2012-03-23 12:54:16

回答

1

这应该做你正在寻找。我刚刚在css中设置了容器和图像的高度,但是如果它们在html中使用相同的设置或使用javascript,结果应该是相同的。背景颜色只是为了清晰。

#container { 
background-color: #333; 
height: 200px; 
} 
#image{ 
height: 200px; 
float: left; 
} 
#contents{ 
line-height: 200px; 
float: left; 
position: fixed; 
} 

编辑:这是使用旧的经典保证金自动招解决方案的小提琴。这里可能会导致问题的唯一原因是父母需要成为职位:固定;这可能会在其他地方引发问题。主要的是它的工作原理,并没有使用像素设置高度。

link

下面是从小提琴为无定高度纯的CSS溶液的代码。

<div id="container"> 
    <img id="image" src="https://www.google.co.uk/logos/2012/juan_gris-2012-hp.jpg" /> 
    <div id="contents">Contents</div> 
</div> 

#container { 
    position: fixed; 
} 
#contents{ 
    position: absolute; 
    top: 0; 
    bottom: 0; 
    left: 0; 
    right: 0; 
    width: 50%; 
    height: 10%; 
    margin: auto; 
} 
+1

来自OP“所有高度都是动态的(它们在窗口大小调整时发生变化)。“ – justanotherhobbyist 2012-03-22 12:56:56

+0

不可接受,如上所述,没有高度是固定的 – Sergey 2012-03-22 16:50:57

+0

@SergeySedykh我编辑了这个,检查出一个工作实现的小提琴 – Andrew 2012-03-23 13:36:47

1

#contents的高度是已知的吗?在这种情况下,这应该这样做(jsfiddle demo):

#container{ 
    position:relative; 

    /* For demo only */ 
    height:500px; 
    border: 5px solid red; 
} 
#image{ 
    position:absolute; 

    /* For demo only */ 
    height:500px; 
} 

#contents{ 
    position: absolute; 
    top:50%; 

    height:100px; 
    margin-top: -50px; /* Half of #contents height */ 

    /* For demo only */ 
    background-color: blue; 
} 
+1

从OP”所有的高度是动态的(他们改变窗口大小)“ – justanotherhobbyist 2012-03-22 12:56:46

+0

Ai,误读,虽然他只是指图像和容器的高度 – Supr 2012-03-22 12:59:17

+0

不可接受,如上所述,没有高度是固定的 – Sergey 2012-03-22 16:51:13

0

如果你知道#contents的高度,你可以设置

#container{position:relative;} 
#contents{ 
    position:absolute; 
    top:50%; /*50% of parent*/ 
    margin-top:/*negative one-half of container height i.e. if contaner is 4 em -2em* 
} 

你说你不知道的#contents的高度,虽然。

另一种选择是将显示器设置:以table-cell和使用vertical-align: middle

#container{ 
    display: table-cell; 
    vertical-align: middle; 
} 

但是这取决于你的浏览器是靶向的支持,可能会导致显示问题为好。

更确保消防方式是第一选择一些jQuery的或javascript相结合,发现元素的高度并设置它的上边距:

content= document.getElementById('content') 
content.style.marginTop = '-' + content.offsetHeight + 'px'; 

http://jsfiddle.net/h76sy/

编辑:对不起,在我的JavaScript中有一个错误,现在就试试吧

+0

关于JS解决方案 - 这是我现在与jQuery调整大小()组合使用。它在页面加载时工作良好,并通过拖动窗口边缘来调整大小,但是它在窗口最大化/恢复方面存在bug。 – Sergey 2012-03-22 17:08:05

+0

我认为我必须更深入地研究'table-cell'解决方案 – Sergey 2012-03-22 17:09:09

+0

'table-cell'也不会工作:'table-cell'中有两个对象,都是未知高度:图像和div。 – Sergey 2012-03-22 18:21:01