我设计了Web应用程序的外观和布局,其目标是响应性设计,并针对不同的设备尺寸进行尽可能小的更改(媒体查询)。

我整理了一个我能想到的最小示例,其中显示了一个header-div和一个vcenter-div。 (实际上,我有更多的内联块列。)无论如何,我想垂直对齐(居中)所有div-inline-blocks。在演示中,我在.header:before中有一个伪内联块,在.vcenter中有另一个内联块。

在vcenter-block中,我有一个Google徽标图片。考虑到响应速度,我希望Google图片的大小是.header-div的20%(不是.header .vcenter-div,因此.header .vcenter-div上没有给出高度)。

这有时效果很好,有时效果不佳!在JSFiddle上,我有一个不起作用的演示:
https://jsfiddle.net/cfneikter/sy5w69f1/7/

在另一台服务器上,我有完全相同的演示,可以在其中运行:
https://app04.azurewebsites.net/test.html

这让我发疯。 Safari和Google Chrome的行为相同。但是有什么区别呢? :)

CSS非常简单:

body, html {
    height: 100%;
    width: 100%;
}

.header {
    height: 20%;
    font-size: 1.0em;
    position: relative;
    background-color: #cacaca;
}

.header:before {
    content: '';
    display: inline-block;
    vertical-align: middle;
    height: 100%;
}

.header .vcenter {
    display: inline-block;
    vertical-align: middle;
    width: 35%;
    text-align: left;
    color: #acacac;
}

.header .vcenter img {
    height: 20%; /* why is percent isn't working (sometimes)!?*/
    width: auto;
}


HTML也是如此:

<div class="header">
    <div class="vcenter">
        <img src="some_image.png" />
    </div>
</div>

最佳答案

在vcenter div上添加height: 100%




body, html {
height: 100%;
width: 100%;
}

.header {
height: 20%;
font-size: 1.0em;
position: relative;
background-color: #cacaca;
}

.header .vcenter {
display: inline-block;
width: 35%;
text-align: left;
color: #acacac;
height: 100%;
}

.header .vcenter img {
height: 20%; /* why is percent isn't working!?*/
width: auto;
position: absolute;
top: 50%;
transform: translatey(-50%);
}

<div class="header">
	<div class="vcenter">
		<img src="http://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" />
	</div>
</div>





编辑
使用flex做您需要的另一种方法




body, html {
height: 100%;
width: 100%;
}

.header {
height: 20%;
font-size: 1.0em;
background-color: #cacaca;
}

.header .vcenter {
width: 35%;
display: flex;
align-items: center;
text-align: left;
color: #acacac;
height: 100%;
}

.header .vcenter img {
height: 20%; /* why is percent isn't working!?*/
width: auto;
}

<div class="header">
	<div class="vcenter">
		<img src="http://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" />
	</div>
</div>

10-05 20:58
查看更多