繁体   English   中英

如何将此跨度对齐到 div 的右侧?

[英]How to align this span to the right of the div?

我有以下 HTML:

<div class="title">
    <span>Cumulative performance</span>
    <span>20/02/2011</span>
</div>

使用这个 CSS:

.title
{
    display: block;
    border-top: 4px solid #a7a59b;
    background-color: #f6e9d9;
    height: 22px;
    line-height: 22px;
    padding: 4px 6px;
    font-size: 14px;
    color: #000;
    margin-bottom: 13px;
    clear:both;
}

如果你检查这个 jsFiddle:http: //jsfiddle.net/8JwhZ/

您可以看到名称和日期粘在一起。 有没有办法让日期对齐到右边? 我试过float: right; 在第二个<span>但它搞砸了样式,并将日期推到了封闭的 div 之外

如果可以修改 HTML:http: //jsfiddle.net/8JwhZ/3/

<div class="title">
  <span class="name">Cumulative performance</span>
  <span class="date">20/02/2011</span>
</div>

.title .date { float:right }
.title .name { float:left }

使用浮点数有点混乱:

这和许多其他“琐碎”的布局技巧一样可以用 flexbox 来完成。

   div.container {
     display: flex;
     justify-content: space-between;
   }

在 2017 年,如果您不必支持旧版浏览器,我认为这是首选解决方案(优于浮动): https ://caniuse.com/#feat=flexbox

检查 fiddle 与 flexbox 相比不同的浮动用法(“可能包括一些竞争答案”): https ://jsfiddle.net/b244s19k/25/。 如果你仍然需要坚持浮动,我当然推荐第三个版本。

浮动的另一种解决方案是使用绝对定位:

.title {
  position: relative;
}

.title span:last-child {
  position: absolute;
  right: 6px;   /* must be equal to parent's right padding */
}

另见小提琴

使用没有justify-content: space-between flexbox 的解决方案。

<div class="title">
  <span>Cumulative performance</span>
  <span>20/02/2011</span>
</div>

.title {
  display: flex;
}

span:first-of-type {
  flex: 1;
}

当我们在第一个<span>上使用flex:1时,它会占用整个剩余空间并将第二个<span>向右移动。 这个解决方案的小提琴: https ://jsfiddle.net/2k1vryn7/

在这里https://jsfiddle.net/7wvx2uLp/3/你可以看到两种 flexbox 方法之间的区别:flexbox with justify-content: space-between和 flexbox with flex:1 on the first <span>

您可以在不修改 html 的情况下执行此操作。 http://jsfiddle.net/8JwhZ/1085/

<div class="title">
<span>Cumulative performance</span>
<span>20/02/2011</span>
</div>

.title span:nth-of-type(1) { float:right }
.title span:nth-of-type(2) { float:left }
ul { /** works with ol too **/
    list-style: none; /** removes bullet points/numbering **/
    padding-left: 0px; /** removes actual indentation **/
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM