【问题标题】:How do I vertically align a form element and an img link inside a div如何垂直对齐 div 内的表单元素和 img 链接
【发布时间】:2011-12-27 02:20:38
【问题描述】:

我正在尝试将表单元素(搜索表单)和 div 内的 img 链接对齐。我试过做'display:inline',将它们设置在同一行,但不是预期的。我还尝试使用填充或边距调整宽度、浮动和定位,但均无济于事。我将它们放在自己的 div 中,认为这可能会有所帮助,但我也没有取得任何成功。我在这里做错了什么?我知道我的代码在风格上可能看起来很糟糕,但这是他们的容器 div 和里面的代码:

<DIV style="BORDER-BOTTOM: 1px solid; BORDER-LEFT: 1px solid; BACKGROUND-COLOR: rgb(127,137,155); MARGIN: 3% auto auto; WIDTH: 670px; HEIGHT: 60px; BORDER-TOP: 1px solid; BORDER-RIGHT: 1px solid" id=links>
  <div style="border:0px;width:330px;display:inline;float:left; height:45px; margin-left:4%;margin-top:5%;margin-bottom:5%;"><FORM method=post name=search action=http://dummysearchaddress/search><INPUT name=searchText> <INPUT value="Knowledge Base Search" type=submit> </FORM></div>
  <div style="border:0px;width:300px;display:inline;height:55px; margin-left:3%;margin-top:20%;margin-bottom:5%;"><A href="http://dummyimg"><IMG style="BORDER-BOTTOM: rgb(0,0,0) 1px solid; BORDER-LEFT: rgb(0,0,0) 1px solid;BORDER-TOP: rgb(0,0,0) 1px solid; BORDER-RIGHT: rgb(0,0,0) 1px solid;" alt="Technical Support Manual" src="file:///C:/Users/Instructor/Desktop/img/Tech_Manual_button_204%20by%2027.png"></A>     </div>
</DIV>

非常感谢任何帮助!

【问题讨论】:

  • 您是否尝试过将vertical-align: middle; 放在&lt;img&gt; 标记样式中?
  • 你想要this这样的东西吗?

标签: html css forms image vertical-alignment


【解决方案1】:

将要垂直对齐的元素放在一个 div 中,并使用display: table-cellvertical-align: middle,如下所示:

<div class="center" style="height:300px">
    <img ...>
    <form ...>
</div>

<style type="text/css">
.center {
     display:table-cell;
     vertical-align:middle;
}

/* put the two elements next to each other */
.center img, .center form {
     display: inline-block;
}
</style>

还可以考虑将样式定义放在单独的 css 块/文件中。

【讨论】:

  • @Sooper,是的,我试过了,它奇怪地对齐了它们,我在一个上尝试了 vertical-align:middle,然后在另一个上尝试了 vertical-align:(x%) 以正确对齐它们,但是它似乎只适用于 ie9
  • @Ronak,感谢您的尝试,但没有。我希望 img/form 处于同一垂直水平。
  • 谢谢 Parzifal,我相信您的解决方案有效。但是,更改容器 div 使其在其容器 div 中的定位发生了变化。我尝试通过更改边距/填充来重新定位,但没有运气。现在看起来很好,因为我刚刚扩展了宽度以使其成为一个完整的盒子,但是我知道将来,这样做是否有任何具体原因会抑制我移动 div 的能力?不管怎样,谢谢你!
  • 是的,当您指定 display: table-cell 时,您不能再使用 margin,因为 table-cell 的边距通常由周围的表格计算(属性边框间距和边框折叠)。如果您想添加边距,请用另一个容器 div 将 div 包围并在其中添加边距,或者如果适用,请向父元素添加填充。
猜你喜欢
  • 2014-03-03
  • 2013-04-17
  • 2017-09-28
  • 1970-01-01
  • 2012-06-14
  • 2011-10-04
  • 2018-09-24
  • 2010-09-09
相关资源
最近更新 更多