Align 2 span one left and the other right inside a

2019-02-19 02:22发布

问题:

Could anybody write the CSS fragment to do this?

<div class="container">
  <span class="left">Left</span><span class="right">Right</span>
</div>

Here's the CSS for .container:

.container {
    position:absolute;
    bottom:0;
    margin: 0 5px 5px 5px;
}

Notice the position is absolute because it is "absolute positionated" on its containing element.

I've alredy tried float:left/float:right on the two nested elements but nothing happens.

回答1:

Set the elements to block, set a width and float them.

.left{
  display: block;
  float:left;
  width: 100px;
}

.right{
  display: block;
  float:right;
  width: 100px;
}

Example: http://jsfiddle.net/LML2e/



回答2:

float: left and float: right will work perfectly when you set a (relative or absolute) width for your .container div

Demo

.container {
    position:absolute;
    bottom:0;
    margin: 0 5px 5px 5px;
    width: 200px; //either absolute width
    width: 100%;  // or relative width
}

Side note: If you set the .container to width: 100% you will get ugly scroll bars due to the margin. Just use the margin in the .left and .right classes. See here.



回答3:

You need to set a width in order to use float. If you want a width of 100% you can set .container { width: 100%; } or improve your code into something like:

.container {
    position:absolute;
    bottom:5px;
    left:5px;
    right:5px;
}