0

我需要在一行中显示字符串“field1 field2 field3”,field1、field2 和 field3 将是 N 个字符。

我怎样才能显示字符串?

<style>
#div1{
    width:1000px;
    border:1px solid;
}           
.field1{
    display:inline;
    width:auto;
}
.field2{
    display:inline;
    width:auto;
}
.field3{

    width:auto;
}
        </style>

        <div id="div1">
            <div class="field1">Field1(with N number of characters)</div>
            <div class="field2">Field2(with N number of characters)</div>
            <div class="field3">Field3(with N number of characters)</div>
        </div>
4

4 回答 4

1

除了将所有块级子项(包括 last div)转换为内联布局外,您可能还需要防止换行。在最简单的情况下,您可以将样式表替换为:

#div1 {
  white-space: nowrap;
  border: 1px solid;
}           
#div1 div {
  display: inline;
}

如果您有其他原因,您可以在元素上设置宽度,但上面的代码也可以在没有此类设置的情况下工作。

于 2012-10-19T14:30:38.237 回答
0

我想这是你想要的

<style>
#div1{
width:auto;
border:1px solid;
 }           
.field1{
display:inline;
width:auto;
}
 .field2{
display:inline;
width:auto;
}
.field3{
display:inline;
width:auto;
 }
    </style>

    <div id="div1">
        <div class="field1">Field1(with N number of characters)</div>
        <div class="field2">Field2(with N number of characters)</div>
        <div class="field3">Field3(with N number of characters)</div>
    </div>​
于 2012-10-19T14:26:50.047 回答
0

正如Sven指出的,您可以使用跨度。没有任何 CSS 更改,您的所有项目将彼此相邻显示。

您的另一个选择是浮动 div,如下所示:

    <div id="div1">
        <div class="field1 fl">Field1(with N number of characters)</div>
        <div class="field2 fl">Field2(with N number of characters)</div>
        <div class="field3 fl">Field3(with N number of characters)</div>
        <div class="clear"></div><!-- This makes sure you don't float unintended elements in older browsers -->
    </div>

并将其添加到您的 css 中(另外,删除您的display: inline;规则):

.fl {
  float: left;
}

.clear {
  clear: both;
}

field1如果,field2或的内容field3是动态的(例如使用 javascript 将文本替换为其他内容),则您可能希望使用 div ;但是如果您确定要放入元素中的只是文本,那么使用 span 就可以了(示例):

    <div id="div1">
        <span class="field1">Field1(with N number of characters)</span>
        <span class="field2">Field2(with N number of characters)</span>
        <span class="field3">Field3(with N number of characters)</span>
    </div>
于 2012-10-19T14:29:28.890 回答
0

您不应该为每个项目需要单独的类,如果它们都将排成一行,您可以只使用一个可以完成这项工作的类(除非您稍后要引用特定的类)。:after 将确保该行之后的任何内容都不会出现在同一行上。

<style>
    .field {
        display: inline-block;
    }
    .field:after{
        display:block;
        height: 0;
        content: '';
        clear: both;
    }
</style>

<div id="div1">
    <div class="field">Field1(with N number of characters)</div>
    <div class="field">Field2(with N number of characters)</div>
    <div class="field">Field3(with N number of characters)</div>
</div>
于 2012-10-19T14:33:38.850 回答