Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

css - How to align two elements on the same line without changing HTML

I have two elements on the same line floated left and floated right.

<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>

I need for element2 to line up next to element1 with about 10 pixels of padding between the two. The problem is that element2's width can change depending on content and browser (font size, etc.) so it's not always lined up perfectly with element1 (I can't just apply a margin-right and move it over).

I also cannot change the markup.

Is there a uniform way to line them up? I tried margin-right with a percentage, I tried a negative margin on element1 to bring element2 closer (but couldn't get it to work).

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using display:inline-block

#element1 {display:inline-block;margin-right:10px;} 
#element2 {display:inline-block;} 

Example


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...