如何使div在另一个div的两端浮动?

时间:2014-06-07 07:15:13

标签: html css

到目前为止我已尝试过这个,

http://jsfiddle.net/BXSJe/4/

我试图在另一个div的左右两端放置2个div,我尝试使用float:left和float:right但是它们显示在新行中

我想要这样的东西,

  

[[leftcap] ................. TITLE ............... [rightcap]]

我真的很抱歉,我不能代表这一点。

HTML

<div id="shell">
    <div id="title">
        <div id='leftcap'>o</div>
        TITLE HERE
        <div id='rightcap'>x</div>
    </div>
    <div id="content">Content</div>
</div>

CSS

 #shell {
 width:500px;
 height:300px;
 background:lightGrey; 
}

#title {
 background:green;
 padding:5px;
 border-radius:25%;   
 text-align:center;
}
#content
{
    text-align:center;
    vertical-align:center;
}
#leftcap
{
    width:10%;
}
#rightcap
{
    width:10%;
}
#leftcap,#rightcap
{
    height:100%;
    width:10%;
    background:red;
}

UPDATE:使用float属性解决了问题,我还有另一个问题,如何在容器div中垂直居中对齐文本?

3 个答案:

答案 0 :(得分:1)

你需要的是CSS的float属性,它强制元素左右对齐。

更新了小提琴:http://jsfiddle.net/BXSJe/820/

希望这有帮助。 :)

答案 1 :(得分:1)

您需要创建HTML:

<div id="mainDiv">
    <div id="floatLeft">Left floated text here</div>
    <div id="floatRight">Right floated text here</div>
</div>

和CSS这样:

div {
    background-color: Red;
    height:100px;
    width: 100%;
}

#floatLeft {
    width:100px;
    float:left;
    background-color: Blue;
}

#floatRight {
    width:100px;
    float:right;
    background-color: Gray;
}

你可以在这里看到这一点 - &gt; http://jsfiddle.net/g6U8n/

希望这有帮助!!!

答案 2 :(得分:1)

您的相同代码只需要添加一些属性,请看这里

<div id="shell">
    <div id="title">
        <div id='leftcap'>o</div>
        TITLE HERE
        <div id='rightcap'>x</div>
    </div>
    <div id="content">Content</div>
</div>

CSS

#shell {
 width:500px;
 height:300px;
 background:lightGrey; 
}

#title {
 background:green;
 padding:5px;
 border-radius:25%;   
 text-align:center;
}
#content
{
    text-align:center;
    vertical-align:center;
}
#leftcap
{
    width:10%;
    display:inline-block;
    float:left;
}
#rightcap
{
    width:10%;
    display:inline-block;
    float:right;
}
#leftcap,#rightcap
{
    height:100%;
    width:10%;
    background:red;
}

希望这是有效的;)