简体   繁体   English

如何在同一行中对齐两个元素,而不会重叠

[英]How to align two elements in the same line,without overlap

I want to align two elements,in the same line,like this: click here 我想在同一行中对齐两个元素,例如: 单击此处

full code 完整的代码

<div id="element1">  element 1 markup </div> 
<div id="element2">  element 2 markup </div> 

css CSS

#element1 {
    display:inline-block;
    margin-right:10px; 
    width:200px; 
    background-color:red;
} 
#element2 {
     display:inline-block; 
     width:200px;
     background-color:red;
} 

Also,without overlapping each other.For example if a have a parent div,and two child divs. 另外,彼此之间不重叠。例如,如果a有一个父div和两个子div。 The parent div,have 1000px width,and the childs have 500px each,so they fit. 父级div的宽度为1000像素,子级的div的宽度为500像素,因此适合。 But if i resize the first div to 600px,i want the second one to auto resize,and keep staying inline,without changing his position,or the first to overlap the second. 但是,如果我将第一个div的大小调整为600px,我希望第二个div自动调整大小,并保持在线状态,而无需更改其位置,或者第一个与第二个重叠。 In the fiddle above,they are aligned in the same line,but doesnt matter what i do,the second one changes his position instead resizing,or they overlap each other. 在上面的小提琴中,它们对齐在同一行中,但是无论我做什么,第二个都改变其位置而不是调整大小,或者它们彼此重叠。 Any idea? 任何想法?

I know it must be done with percentage,but is not working either 我知道必须用百分比完成,但也无法正常工作

The width attribute accepts percentage value, base on its parent (or its nearest parent with the position:relative attribute if the element has the property position set as "absolute" or "fixed"). width属性接受基于其父级(或如果元素的属性位置设置为“绝对”或“固定”,则其与position:relative属性最接近的父级)的百分比值。

So you can use this CSS to the child 这样您就可以将此CSS应用于孩子

#element1 {display:inline-block;margin-right:10px; width:50%; background-color:red;} 
#element2 {display:inline-block; width:50%; background-color:red;} 

PS: If you are using inline-block, you have to make sure that there is no space between the tags, so you HTML must became this PS:如果使用内联块,则必须确保标记之间没有空格,因此HTML必须成为

<div id="element1">  element 1 markup
</div><div id="element2">
element 2 markup </div> 

Check this jsfiddle to see if it is what you wanted. 检查这个jsfiddle ,看看它是否是您想要的。 I'm not using display:inline-block since it looks that it is what's causing the problem. 我没有使用display:inline-block因为它看起来是引起问题的原因。 If you don't mind using floats, then this is your answer. 如果您不介意使用浮点数,那么这就是您的答案。

EDIT: 编辑:

Check this resource here to see/correct your problem. 在此处检查此资源以查看/更正您的问题。

http://jsfiddle.net/a4aME/507/ http://jsfiddle.net/a4aME/507/

#element1 {width:50%; background-color:red;float:left} 
#element2 {width:50%; background-color:red;float:left} 

Take off the the display: and float it all left. 取下显示屏:将其全部浮动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM