【问题标题】:Vertical align any inline element in any div using margin-auto使用margin-auto垂直对齐任何div中的任何内联元素
【发布时间】:2012-05-26 15:47:48
【问题描述】:

我正在设计一个文本字段,我希望它垂直显示在 div 的中间。我希望黑色 div 垂直显示在蓝色 (id=srch) div 的中心。

HTML 和 CSS:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style type="text/css">

* {
    vertical-align:baseline;
    font-weight: inherit;
    font-family: inherit;
    font-style: inherit;
    font-size: 100%;
    border:0 none;
    outline:0;
    padding:0;
    margin:0;   
}
html {
    height:100%;
}

#outerwrapper {
    width: 90%;
    height: 100%;
    min-height: 100%;
    height: auto !important;
    border: solid thin #333;
}
body {
    height: 100%;
    width: 100%;
}
#header {
    height: 80px;
    width: 100%;
    background-color:#999;
}
input {
    border:solid thin #ab1; 
}
#srch{
    height:50px;
    background-color:#00f;
}
#srch div{
    margin: auto 0 auto 0;
    width: 200px;
    background-color: #000;
}
#contentWrapper {
    width: 100%;
    overflow: auto;
    background-color:#0F0
}

</style>
</head>

<body>
<div id="outerwrapper">
  <div id="header">Header

      <div id="srch">
        <div>
            <input type="tel" name="aa"/>
        </div>
      </div>
  </div>

  <div id="contentWrapper">
    Content Wrapper
  </div>  

</div>
</body>
</html>

我的方法:我将黑色 div 的顶部和底部边距设为自动,但它不起作用(对于水平中心 [左右 margin:auto] 它也起作用)。 margin:auto 只对左右有效吗?

我想知道为什么会这样,我不想要任何其他解决方案,例如:

  1. 使用垂直对齐的 div 内嵌显示文本。
  2. 以适当的填充或边距显示。

【问题讨论】:

    标签: css html margin vertical-alignment


    【解决方案1】:

    margin: auto 不适用于顶部和底部。如果指定了margin-top: automargin-bottom: auto,则their used value is 0。这是article about how you can achieve vertical centering

    【讨论】:

      【解决方案2】:

      你需要在这里使用一些 jQuery 来计算父容器的高度。

      演示 - http://jsfiddle.net/tQBVy/

      【讨论】:

      • 在这种情况下,父容器有一个静态高度,很容易找到一个好的边距值。没有必要做的比必要的更复杂。
      • 您在帖子中链接的文章是一个静态解决方案,但是通过我给您的小提琴,您可以对任何元素使用 vAlign 函数并使其垂直居中。我想这个功能使它更容易。让我知道你的评论
      • 是的,但是在OP发布的代码中也有一个静态解决方案,不需要动态计算高度。我绝对可以看到像这样的东西需要动态解决方案,但在这种特殊情况下不是。顺便说一句,我喜欢你的解决方案!
      • 在这种情况下投票会更好 :-) 干杯!
      • +1 但我不一定认为在这种情况下这是一个好的解决方案。 :)
      猜你喜欢
      • 2015-04-18
      • 2011-07-17
      • 1970-01-01
      • 2013-04-11
      • 2012-09-07
      • 2014-01-22
      • 2010-09-09
      相关资源
      最近更新 更多