CSS:在div中对齐元素

luq*_*ita 3 html css positioning

我有一个包含三个元素的div,但在正确放置最后一个元素时遇到问题。左侧的div必须在左侧,中间的div必须居中,而第三个div必须在右侧。

所以,我有这样的事情:

#left-element {
    margin-left: 9px;
    margin-top: 3px;
    float:left;
    width: 13px;
}

#middle-element {
    margin:0 auto;
    text-align: center;
    width: 300px;
}

#right-element {
    float:right;
    width: 100px;
}
Run Code Online (Sandbox Code Playgroud)

我的html看起来像这样:

   <div id="container-div">
        <div id="left-element">
            <img src="images/left_element.png" alt="left"/>
        </div>
        <div id="middle-element">
            I am the text inside the middle element
        </div>
        <div id="right-element">
            I am the text in right element
        </div>
    </div>
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

谢谢!

lpd*_*lpd 5

您尚未为容器div包含css,但是只要其中包含浮动元素,就应该像这样隐藏溢出:

#container {
  overflow: hidden;
  width: 100%; /* for good measure */
}
Run Code Online (Sandbox Code Playgroud)

当您放置中间div时,您将设置跨整个容器的边距,因此所有其他元素都将定位在下面的行上。注意,至少对于大多数现代浏览器,进一步。如果您对元素重新排序,如下所示:

<div id="container">
    <div id="left-element">
        <img src="images/left_element.png" alt="left"/>
    </div>
    <div id="right-element">
        I am the text in right element
    </div>
    <div id="middle-element">
        I am the text inside the middle element
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

您应该会发现它有效。更好的方法,因为我不能肯定这是否是应该工作,是使用CSS定位。应用以下CSS:

#container {
  overflow: hidden;
  width: 100%;
  min-height: 36px; /* Remember absolute positioning is outside the page flow! */
  position: relative;
}
#left-element {
  position: absolute;
  left: 9px;
  top: 3px;
  width: 13px;
}
#middle-element {
  margin: 0 auto;
  text-align: center;
  width: 300px;
}
#right-element {
  position: absolute;
  right: 0px;
  top: 0px;
  width: 100px;
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*ler 1

我认为你的问题是你浮动了左侧和右侧的元素,但没有浮动中心的元素。尝试这样的事情:

CSS:

<style>
    #container { display:block; margin:0; padding:0; width:640px; height:400px; outline:1px solid #000; }
        #left-element { float:left; display:block; margin:10px; padding:0; width:200px; height:380px; background:#ccc; }
        #middle-element { float:left; display:block; margin:10px 0; padding:0; width:200px; height:380px; background:#eaeaea; }
        #right-element { float:left; display:block; margin:10px; padding:0; width:200px; height:380px; background:#ddd; }
</style>
Run Code Online (Sandbox Code Playgroud)

HTML:

<div id="container">
    <div id="left-element">Left Element</div>
    <div id="middle-element">Middle Element</div>
    <div id="right-element">Right Element</div>
</div>
Run Code Online (Sandbox Code Playgroud)