简体   繁体   English

在容器内对齐嵌套div的左右

[英]aligning nested div's left and right inside container

I am trying to create a div which is as wide as the page and has two div's inside it, one which is aligned left and one aligned right. 我正在尝试创建一个与页面一样宽的div,并在其中包含两个div,其中一个div左对齐,另一个右对齐。 Its' turning out to be a lot more difficult than I expected. 结果比我预想的要困难得多。 With the code below, both div's align left. 使用下面的代码,两个div都向左对齐。 I have made a jsFidle to demonstrate the problem. 我做了一个jsFidle来演示这个问题。 Thanks for reading. 谢谢阅读。

<style>

#container{
            border:1px solid;
}

#left{
       text-align:left;
       border:1px solid red;
       display:table-cell;
}

#right{
       text-align:right;
       border:1px solid blue;
       display:table-cell;
}

</style>

<body>

  <div id = "container">
    <div id = "left">far left</div>
    <div id = "right">far right</div>
  </div>   

</body>

There's no need to use floating elements or absolute positioning in general for something like this. 像这样的东西通常不需要使用浮动元素或绝对定位。
It's an approach that should've stopped along with using tables for general layouts. 在将表用于常规布局时,应该停止使用这种方法。

Sample Jsfiddle 样本Jsfiddle

CSS: CSS:

#container {
    display: table;
    width: 100%;
}

#container > div {
    display: table-cell;
}

.right {
    text-align: right;
}

HTML: HTML:

<div id="container">
    <div>
        <p>Left</p>
    </div>
    <div class="right">
        <p>Right</p>
    </div>
</div>

You need to use 您需要使用

float: left 

and

float: right

on the divs. 在divs上。

A cooler way of aligning things is to use 对齐事物的一种比较酷的方法是使用

display:flex

on the container, but you'll have to check the browser compatibility for that I'm afraid. 在容器上,但恐怕您必须检查浏览器的兼容性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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