如何使用自动换行对齐两个浮动HTML标记?

时间:2015-12-03 05:28:42

标签: javascript html css

我正在尝试将另一侧面向正确的两个浮动HTML元素对齐。 下面的HTML更清晰。

label{
  float:left;
  width:20%;
  padding-right:2.5%;
  word-wrap:break-word;
  background:red;
}
span{
  float:right;
  width:75%;
  padding-left:2.5%;
  word-wrap:break-word;
  background:green;
}
<div>
  <p>
    <label>OrderId:</label>
    <span>4857924875928475924</span>
  </p>
  <p>
    <label>Comment:</label>
 <span>This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text.</span>
  </p>
  <p>
    <label>User:</label>
    <span>User_Name</span>
  </p>
</div>

当评论足够长时,上面的脚本错误对象:User_Name。

我在这里缺少什么?

由于

2 个答案:

答案 0 :(得分:4)

定义 p tag p{overflow:hidden;}

因为您使用了浮动 元素,只需清除p tag

label{
  float:left;
  width:20%;
  padding-right:2.5%;
  word-wrap:break-word;
  background:red;
}
p{overflow:hidden;}
span{
  float:right;
  width:75%;
  padding-left:2.5%;
  word-wrap:break-word;
  background:green;
}
<div>
  <p>
    <label>OrderId:</label>
    <span>4857924875928475924</span>
  </p>
  <p>
    <label>Comment:</label>
 <span>This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text.</span>
  </p>
  <p>
    <label>User:</label>
    <span>User_Name</span>
  </p>
</div>

more about this

答案 1 :(得分:3)

您可以使用flexbox实现相等高度的列。

HTML (无更改)

<强> CSS

p {
  display: flex;
}

label {
  flex: 1 1 20%;
  padding-right: 2.5%;
  word-wrap: break-word;
  background: red;
}

span {
  flex: 1 1 75%;
  padding-left: 2.5%;
  word-wrap: break-word;
  background: green;
}

DEMO

Flexbox的好处:

  1. 最小代码;效率很高
  2. centering, both vertically and horizontally, is simple and easy
  3. equal height columns are simple and easy
  4. multiple options for aligning flex items
  5. 它的响应
  6. 与浮动不同,浮动提供有限的布局容量,因为它们从未用于构建布局,因此flexbox是一种现代(CSS3)技术,具有广泛的选项。
  7. 请注意,所有主流浏览器except IE 8 & 9都支持flexbox。最近的一些浏览器版本,例如Safari 8和IE10,需要vendor prefixes。要快速添加所需的所有前缀,请在左侧面板中发布CSS:Autoprefixer