在同一行上左右对齐文本

3
以下代码会在文本上方和下方各显示一条水平线。需要的效果是只在文本上方显示一条水平线,下方同理:

.alignleft {
  float: left;
}

.alignright {
  float: right;
}
<div style="width:800px;">
  <hr />
  <p class="alignleft">To Left: 1024-0038</p>
  <p class="alignright">To Right: 01-15-131194</p>
  <hr />
</div>

显示:文本下应该显示一个hr,它的宽度应该与另一个覆盖整个

宽度的hr相同。 enter image description here

5个回答

7

您可以通过使用div的边框轻松维护对齐,并替换<hr>元素,这样看起来更清洁:

<style>
  div {
    border-top: 1px solid gray;
    border-bottom: 1px solid gray;
    display: flex;
    justify-content: space-between;
    width: 800px;
  }
</style>
<div>
  <p>To Left: 1024-0038</p>
  <p>To Right: 01-15-131194</p>
</div>


@G-Cyr 实际上,@BrandonBrickyKerr 所建议的正是我想要的。但我也理解你的观点,因为帖子没有明确指出我的目标是什么。另外,感谢你编辑我的帖子 - 现在更易读了。 - nam
@BrandonBrickyKerr 我做了一个小改变,使用了 div.myClass {...}<div class="myClass">...</div>。这样可以避免其他 div 受到你建议的样式的影响。但是你回答了我所问的问题(谢谢)。这条评论只是为了其他读者的好处。 - nam

4
请尝试以下方法:

.alignleft {
    float: left;
}

.alignright {
    float: right;
}
hr {
clear:both;
}
<div style="width:800px;">
    <hr />
    <p class="alignleft">To Left: 1024-0038</p>
    <p class="alignright">To Right: 01-15-131194</p>
    <hr />
</div>


2
浮动需要清除。有许多不同的方法可以做到这一点。其中之一是: <hr style="clear: both"/>

0
在文本后面使用 clear:both。像这样:

<style>
.alignleft {
    float: left;
}

.alignright {
    float: right;
}
.clear{
clear:both;
}
</style>
<div style="width:800px;">
    <hr />
    <p class="alignleft">To Left: 1024-0038</p>
    <p class="alignright">To Right: 01-15-131194</p>
    <div class="clear"></div>
    <hr />
</div>

0

首先,float并不是你想象中的那样。

其次,请尝试这个:

  #container{
      width:100%
      }
    .alignleft {
      width:50%;
      float:left;
      text-align: left;
    }

    .alignright {
      width:50%;
      float:left;
      text-align: right;
    }
   hr{
     clear:both;
    }

函数式编程示例:https://jsfiddle.net/catbadger/0d144khk/1/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接