【问题标题】:How to change alignment of certain inline-block elements within a DIV?如何更改 DIV 中某些内联块元素的对齐方式?
【发布时间】:2012-09-05 18:13:40
【问题描述】:

我正在尝试实现一个 inline-block 元素,左对齐,另一个右对齐,而不改变它们的显示类型。

我想要一个 CSS 版本,否则我也可以使用 jQuery 方法。

我的意思是,我只是想显示前两个按钮在左侧对齐,第三个按钮在右侧对齐。

jsBin not working example

<table>
    <thead>
      <tr>
        <th>
          <div style="background-color: lightblue; width: 600px;">
            <span style="display: inline-block; height:20px; background-color: red; margin: 5px 3px;float: left;">
              Button
            </span>

            <span style="display: inline-block; height:20px; background-color: red; margin: 5px 3px; float:right;">
              Button right
            </span>
        </div>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr><td>where did the background of the header cell go? the background is still there if the elements do not float.</td></tr>
    </tbody>
  </table>

【问题讨论】:

  • 请在您的帖子中包含问题代码以及jsbin链接(meta.stackexchange.com/questions/84342/…
  • 左对齐是什么意思?是否将整个元素移动到左侧或其中的文本。
  • @SatyaTeja 我的意思是右对齐,我会更正帖子
  • 但是,这些是内联的,没有设置宽度。如何对连续的内联元素进行交替对齐?目前尚不清楚您希望结果是什么样的。
  • @Toskan 请看一下,我已将您的按钮对齐在右侧。告诉我这是不是你要找的东西?

标签: jquery css alignment


【解决方案1】:

只需将属性 float:right 设置为您的 span 元素。

Working Example

在您在评论中提供的第二个示例中,即带有表格的示例中,您只是遇到了这个问题,因为您没有将样式设置为th 标记,而是设置为div 标记。如果你将background-colorwidth的属性设置为th标签,你会得到你想要的。

Another Working Example

【讨论】:

  • 这是绝对正确的。这正是我想要的样子。问题首先是浮动的。我在我的场景中使用了浮点数,这就是发生的事情:jsbin.com/ibifoq/11/edit 我认为它总是会发生,但它似乎只发生在表格中。有什么想法吗?
  • 添加这一点我想在这里参考一个相关的问题:stackoverflow.com/questions/12407541/…
  • @Toskan 你刚刚做到了。 :) 如果他们有兴趣,人们会阅读我们的 cmets 并点击您的链接!
【解决方案2】:

&lt;span&gt; 本身就是内联块元素——因此不需要声明。您还可以将 CSS 应用于 &lt;th&gt; 元素,而不是将所有内容包装在 &lt;div&gt; 中,并使用 :last-child。从技术上讲,您可以去掉 float:left,但它会导致额外的 CSS 垂直对齐按钮。

CSS
    th { background-color:lightblue; width:600px; }
    th span { background-color:red; float:left; height:20px; margin:5px 3px; }
    th span:last-child { float:right }

HTML
    <th>
        <span>Button</span>
        <span>Button</span>
        <span>Button right</span>
    </th> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 2021-03-16
    相关资源
    最近更新 更多