【问题标题】:using CSS to center FLOATED input elements wrapped in a DIV使用 CSS 将包含在 DIV 中的浮动输入元素居中
【发布时间】:2011-02-25 12:47:03
【问题描述】:

关于居中的问题和答案不乏其人,但鉴于我的具体情况(涉及浮动),我无法让它发挥作用。

我想将一个包含三个浮动输入元素(拆分按钮、文本、复选框)的容器 DIV 居中,这样当我的页面变宽时,它们会从这里开始:

  ||.....[      ][v]     [            ]       [ ] label .....||

到这里

  ||......................[      ][v]     [            ]       [ ] label.......................||

它们漂浮得很好,但是当页面变宽时,它们会停留在左侧:

  ||.....[      ][v]     [            ]       [ ] label .......................................||

如果我删除浮动,以便输入元素堆叠而不是并排:

  [      ][v]   
  [            ]  
  [ ] label

然后当页面调整大小时,它们会正确居中。因此,将浮动应用于容器内的 DIV#hbox 的元素会打乱居中。 由于浮动的设计方式,我想做的事情是不可能的吗?

这是我的 DOCTYPE,标记确实在 w3c 中验证:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

这是我的标记:

 <div id="term1-container">
 <div class="hbox">
    <div>
        <button id="operator1" class="operator-split-button">equals</button>
        <button id="operator1drop">show all operators</button>
    </div>
    <div><input type="text" id="term1"></input></div>
    <div><input type="checkbox" id="meta2"></input><label for="meta2" class="tinylabel">meta</label></div>
 </div>
</div>

这是(不工作的)CSS:

  #term1-container {text-align: center}
  .hbox {margin: 0 auto;}
  .hbox div {float:left; }

我还尝试将 display: inline-block 应用于浮动按钮、文本输入和复选框;尽管我认为它仅适用于文本,但我也尝试将 white-space: nowrap 应用于#term1-container DIV,基于我在 SO 上看到的帖子。 p>

为了更完整一点,这里是创建拆分按钮的 jQuery:

$(".operator-split-button").button().click( function() {
alert( "foo" );
}).next().button( {
text: false,
icons: {
   primary: "ui-icon-triangle-1-s"
    }
}).click( function(){positionOperatorsMenu();} )
})

【问题讨论】:

  • 有什么理由不只在.hbox 上设置宽度并将边距设置为margin: 0 auto;

标签: css css-float centering


【解决方案1】:

CSS:

body {
    text-align: center;
}
#term1-container {
    width: 500px;
    text-align: center;
    margin: 0 auto;
}
.hbox div {
    float: left;
}

HTML

   <div id="term1-container">
     <div class="hbox">
        <div>
         <button id="operator1" class="operator-split-button">equals</button>
         <button id="operator1drop">show all operators</button>
        </div>
       <div><input type="text" id="term1"/></div>
       <div><input type="checkbox" id="meta2"/>
      <label for="meta2" class="tinylabel">meta</label></div>
     </div>
    </div>

更新

如果您在设置固定width: 时遇到问题

你可以使用这样的东西

body {
    text-align: center;
}
#term1-container {
    display: table;
    white-space: nowrap;
    text-align: center;
    margin: 0 auto;
}
.hbox div {
    display: table-cell;
    display: inline
}

【讨论】:

  • 虽然第一个建议的方法没有使浮动表单元素居中,但您的第二个建议(显示:表格单元格;显示:内联)确实使它们居中,但在调整窗口大小时它们不会重新定位.谢谢你的提示。我发现将这些元素包装在字段集中效果最好。
猜你喜欢
  • 2012-07-01
  • 1970-01-01
  • 2013-09-13
  • 2013-04-08
  • 1970-01-01
  • 1970-01-01
  • 2012-07-14
  • 2011-12-14
  • 2012-05-05
相关资源
最近更新 更多