2 <div>在<div> </div> </div>中

时间:2009-12-12 09:42:25

标签: html css

最好的方式中心2 divs内部div。喜欢这个

  1 2 3 4 5 6 7 8 9 10 11 12 
1 ---------------------------
2 -       main div          -
3 -    ------      ------   -
4 -    -div1-      -div2-   -
5 -    ------      ------   -
6 -                         -
7 ---------------------------

主div的宽度和高度是固定的。

感谢

4 个答案:

答案 0 :(得分:2)

这个怎么样?你需要设置的唯一固定的东西是内部div的边距,但是这不应该有害,因为你没有在这个主题的评论中告诉边缘的任何限制。至于样式,只有边框是纯粹的表现形式,其余的是最低要求的样式。

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 1892901</title>
        <style>
            #main {
                position: relative;
                width: 500px;
                height: 300px;
                border: 1px solid black;
            }
            .inner {
                position: absolute;
                top: 0;
                bottom: 0;
                margin: 20px;
                border: 1px solid black;
            }
            .inner.left {
                left: 0;
                right: 50%;
            }
            .inner.right {
                right: 0;
                left: 50%;
            }
        </style>
    </head>
    <body>
        <div id="main">
            <div class="inner left">inner left</div>
            <div class="inner right">inner right</div>
        </div>
    </body>
</html>

我应该补充一点,strict doctype 非常重要,否则由于box model bug而无法在IE中使用。

答案 1 :(得分:0)

使用css 位置:绝对的; 要么 位置:相对; 并使用left:px;顶部:px;

答案 2 :(得分:-3)

向左浮动一个,向右浮动两个

  <div style="width:100px;">
      <div style="float:right;width:50px;">I m div 1</div>
      <div style="float:left;width:50px;">I m div 2</div>
  </div>

答案 3 :(得分:-4)

一个简单的解决方案可能是使用表格:

<table>
<tr>
<td>Div 1 content here</td><td>Div 2 content here</td>
</tr>
</table>

将每个tds中的内容居中,将为您提供我认为您所追求的内容。

编辑:好的,这会被投票,因为我建议使用表格进行“演示”。在一天结束时,这是有效的。它会给出理想的结果。使用css投票的第一个答案是错误的。我无法看到使用表而不是div会对可维护性或未来的设计更改产生任何影响,或者它会产生任何不同。

编辑2:为了完成我的回答,这是一个例子:

<html>
<head>
</head>
<body>

<style>
  div { width: 100px; height: 30px; border: 1px solid red; margin: 0 auto 0 auto; text-   align: center; }
  table { border: 1px solid blue; width: 400px; }
  td { padding: 20px 0 20px; }
</style>

<table>
<tr>
  <td> <div class="one">div 1</div> </td>
  <td> <div class="one">div 2</div> </td>
</tr>
</table>

</body>
</html>

这将为您提供所需的布局。我在div中添加了一些填充,以演示垂直对齐内容的一种方法。

相关问题