【问题标题】:Centering title when next to toolbar在工具栏旁边居中标题
【发布时间】:2014-08-12 02:11:29
【问题描述】:

我正在尝试制作一个带有很好的居中标题和旁边的工具栏的标题栏。我遇到的问题是,随着工具栏的增长,标题越来越远离中心(并且从一开始就从未真正居中)。我一直在胡思乱想,尝试了几次搜索,但似乎找不到答案。有更多css经验的人可以请教我吗?

HTML

<div>
    <span>
        Section Title
    </span>
    <div class="toolbar">
        <button>Add</button>
        <button>Remove</button>
</div>

CSS

div { background:red;overflow:hidden;  text-align: center; }

span a {
    background:#222;
    color:#fff;
    display:inline-block;

    margin:10px 10px 0 0;
    padding:5px 10px
}

.toolbar {
    float: right;
}

这是一个小提琴: http://jsfiddle.net/scottvossen/cePe3/124/

【问题讨论】:

  • 在我看来是居中的。
  • 提示您在问题中发布代码是有原因的。不要绕着它作弊
  • 是的,终于发现它需要代码而不仅仅是代码块中的链接。我的坏..不要经常发布东西。

标签: html css css-float


【解决方案1】:

您将要在外部 div 上使用 position: relative,在内部 div 上使用 position: absolute。您可以了解更多关于定位 div 的信息here

FIDDLE。我还将文本垂直居中。

HTML

<div id="background">
    <div id="centeroutline">
        <div id="centertext">
        Section Title
        </div>
    </div>
    <div class="toolbar">
        <div id="buttons">        
            <button>Add</button>
            <button>Remove</button>
        </div>
    </div>
</div>

CSS

#background { 
    position:relative;
    background:red;
    overflow:hidden;  
    text-align: center; 
    height:26px;
    width:auto;
}

#buttons{
    position:relative;
}

#centeroutline {
    color:#fff;
    display: table;
    width:100%;
}

#centertext{
    margin:10px 10px 0 0;
    padding:5px 10px;
    display: table-cell; 
    vertical-align: middle;
    width:100%;
    text-align:center;
}

.toolbar {
    right:0;
    top:0;
    position:absolute;
}

【讨论】:

  • 我建议您在答案中添加代码。如果 fiddle 出现故障,代码仍会在 Stack Overflow 上。
  • 很好的答案!在使用上一个答案后,我得出了同样的结论。这更简洁,所以你明白了!。
【解决方案2】:

您可以将position: relative 添加到包含div。然后将工具栏绝对定位在角落。

div{
  position: relative
}

.toolbar{
  position: absolute;
  top: 0;
  right: 0;
}

FIDDLE

【讨论】:

  • 太棒了!似乎对我有用。感谢您的快速回复。
猜你喜欢
  • 2016-02-20
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
  • 2015-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多