我有以下标记:
<div id="all">
<div id="one">one</div>
<div id="two">two</div>
<div id="main">main para goes here</div>
</div>
和以下CSS:
#all{
height: 300px;
background: red;
}
#one{
float: left;
}
#two{
float: right;
}
#main{
margin: 0 auto;
width: 250px;
}
我想垂直对齐,但即使使用伪技术也没有成功。垂直对齐应至少适用于 ie8。
请注意:我无法更改标记。这意味着我无法避免使用 float 。
那么,有什么方法可以让它成功吗?
最佳答案
好吧,使用 CSS float 不会让 float 元素在其容器中垂直对齐(无论使用 CSS flexbox 方法如何)。
因此我会使用 inline-block
,这样我就可以通过 vertical-align: middle
声明来对齐它们。
到目前为止一切顺利,但是 #two
元素必须位于容器的右侧,而不使用 CSS float 。因此我们必须指定列的 width
to reorder the columns via relative
positioning :
要使这种方法在 IE8 上起作用,我们必须对宽度列使用百分比单位。说我们最终会:
#all {
height: 300px;
width: 100%;
font-size: 0; /* To remove the white-space between inline-block columns */
}
#all:before {
content: "";
display: inline-block;
vertical-align: middle;
height: 100%;
}
#one, #two, #main {
display: inline-block;
vertical-align: middle;
position: relative;
font-size: 16px; /* Reset the font-size to the default value */
}
#one, #two { width: 30%; }
#two { left: 40%; text-align: right; } /* Push the column to the right by 40% */
#main{ right: 30%; width: 40%; } /* Pull the column to the left by 30% */
这将适用于 IE8+ (不记得 IE6/7 的要求)。但是,对于 IE9+,我们可以使用 calc()
表达式来指定列的宽度,如下所示:
#one, #two {
width: calc((100% - 250px) / 2);
}
#two{
left: 250px;
text-align: right;
}
#main{
right: calc((100% - 250px) / 2);
width: 250px;
background-color: orange;
}
关于css - 垂直对齐 float 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25359619/