简体   繁体   中英

HTML, align two elements on both sides of the same line

不使用表格,如何在同一行中对齐两个元素(一个在左边,另一个在右边)?

HTML content:

<div class='container'>
  <div class="align-left">left</div>
  <div class="align-right">right</div>
</div>

Style as shown:

.container{ width:100%; }    
.align-left{ float: left;width:50%; }
.align-right{ float: right;width:50%; }

Using float: right; and float:left;

If you want them on the same line, you can use INLINE or INLINE-BLOCK.

 #element1 { display: inline-block; margin-right: 10px; width: 200px; background-color: red; } #element2 { display: inline-block; width: 200px; background-color: red; }
 <div id="element1">element 1 markup</div> <div id="element2">element 2 markup</div>

try this:

<div class="align-left">
  left
</div>
<div class="align-right">
  right
</div>

and the css:

.align-left{
   float: left;
 }

.align-right{
   float: right;
 }

see example here

I have made an example for you to understand the elements a bit better. With using a float you can 'move'(float) elements to a specific side (left or right).

Depending on what you want, you can float everything to the left, which makes every element 'stick' to the other element as long as the width's of the elements do not exceed the parent element width. Otherwise they will 'fall' under the element to fit the width. For instance this code where the container has a width of 600px. Each class 'test' has a width of 250px. This will result in 2 elements next to each other, but the other one will fall under it.

<div class='container green'>
  <div class='test big blue'>a</div>
  <div class='test big red'>b</div>
  <div class='test big yellow'>c</div>
</div>

http://jsfiddle.net/qBR9M/4/

The best way to play with this is the give your elements a background-color, so you can see how the respond.

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