如何在不更改HTML的情况下在同一行上对齐两个元素

use*_*378 73 html css margin css-float

我有两个元素在同一条线上向左浮动并向右浮动.

<style type="text/css">
#element1 {float:left;}
#element2 {float:right;}
</style>

<div id="element1">
 element 1 markup
</div>
<div id="element2">
 element 2 markup
</div>
Run Code Online (Sandbox Code Playgroud)

我需要element2在element1旁边排队,两者之间有大约10个像素的填充.问题是element2的宽度可能会根据内容和浏览器(字体大小等)而改变,因此它并不总是与element1完美排列(我不能只应用margin-right并将其移动).

我也无法改变标记.

是否有统一的方式排列它们?我尝试了一个百分比的margin-right,我在element1上尝试了一个负余量来使element2更接近(但是无法让它工作).

Sam*_*iri 152

运用 display:inline-block

#element1 {display:inline-block;margin-right:10px;} 
#element2 {display:inline-block;} 
Run Code Online (Sandbox Code Playgroud)

  • 我尝试过这个。仅当您设置元素 1 和/或元素 2 的宽度时,它才有效。 (2认同)

dku*_*mar 18

#element1 {float:left;}
#element2 {padding-left : 20px; float:left;}
Run Code Online (Sandbox Code Playgroud)

小提琴:http://jsfiddle.net/sKqZJ/

要么

#element1 {float:left;}
#element2 {margin-left : 20px;float:left;}
Run Code Online (Sandbox Code Playgroud)

小提琴:http://jsfiddle.net/sKqZJ/1/

要么

#element1 {padding-right : 20px; float:left;}
#element2 {float:left;}
Run Code Online (Sandbox Code Playgroud)

小提琴:http://jsfiddle.net/sKqZJ/2/

要么

#element1 {margin-right : 20px; float:left;}
#element2 {float:left;}
Run Code Online (Sandbox Code Playgroud)

小提琴:http://jsfiddle.net/sKqZJ/3/

参考:CSS边距和填充之间的差异


小智 10

<style>
div {
    display: flex;
    justify-content: space-between;  
}
</style>

<div>
    <p>Item one</p>
    <a>Item two</a>
</div>  
Run Code Online (Sandbox Code Playgroud)


Moh*_*lal 5

通过使用display:inline-block; 而且更一般而言,当您有一个display: inline-block;内部元素时,使用父级(除html之外,总是有一个父级)。并且即使窗口缩小(收缩),也迫使他们保持在同一行。为父项添加两个属性:

    white-space: nowrap;
    overflow-x: auto;
Run Code Online (Sandbox Code Playgroud)

这里是一个更格式化的示例,以使其清楚:

.parent {
    white-space: nowrap;
    overflow-x: auto;
}

.children {
   display: inline-block;
   margin-left: 20px; 
}
Run Code Online (Sandbox Code Playgroud)

特别是对于此示例,您可以将上面的内容应用为同伴(我假设父对象是body。如果您未放置正确的父对象,则还可以),如果可能,还可以更改html并为其添加父对象。

body { /*body may pose problem depend on you context, there is no better then have a specific parent*/
        white-space: nowrap;
        overflow-x: auto;
 }

#element1, #element2{ /*you can like put each one separately, if the margin for the first element is not wanted*/
   display: inline-block;
   margin-left: 10px; 
}
Run Code Online (Sandbox Code Playgroud)

记住,white-space: nowrap;并且overlow-x: auto;是你需要迫使他们在一条线的。空白:nowrap; 禁用包装。和overlow-x:auto; 当元素超过帧限制时激活滚动。