简体   繁体   中英

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

#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. The parent div,have 1000px width,and the childs have 500px each,so they fit. 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. 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").

So you can use this CSS to the child

#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

<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. I'm not using display:inline-block since it looks that it is what's causing the problem. 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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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