【问题标题】:Aligning a Child Div in a parent div [duplicate]在父 div 中对齐子 div [重复]
【发布时间】:2023-04-01 22:50:01
【问题描述】:

可能重复:
Make outer div be automaticly the same height as its floating content

我觉得我在这里遗漏了一些非常简单的东西......

我们有一个简单的设置:一个包含子 div 的父 div。 我想:

  • 让父级根据子级调整其高度
  • 将子元素与父元素的右边缘对齐,而不是默认的左边缘。

使用float:right 将导致父级不再正确调整大小,并且子级将“跳出”父级。

我尝试过使用align: righttext-align: right,但目前还没有骰子。

HTML:

    <div id="parent"> <p>parent</p>
        <div class="child"> <p>child</p> </div>

        <div class="child right"> <p>child2</p> </div>
    </div>

CSS:

    div{ padding: 15px; margin: 5px; }
    p{ padding: 0; margin: 0; }

    #parent{
        background-color: orange;
        width: 500px;
    }

    .child{
        background-color: grey;
        height: 200px;
        width: 100px;
    }

    .right{ float: right; } // note: as the commenters suggested I should also be using a float:left on the other child.

Result:

What I want:

关于我可以使用#parent.right 进行更改以使child2 正确对齐的任何建议?

编辑

我为此找到的最佳解决方法是在父级上使用display:table。虽然我没有在 IE 中对此进行测试,但它解决了我关心的浏览器中的问题,并避免使用 cmets 中讨论的不直观的overflow:hidden 方法。

更好的是:将孩子的左边距设置为自动。

【问题讨论】:

标签: css html parent alignment


【解决方案1】:

尝试浮动内容并将overflow: hidden 添加到父级。这是违反直觉的,但对我来说有类似的问题。

编辑:还将第一个孩子浮动到左侧。

【讨论】:

  • 你也可以使用 float:left on .child 和 float:right on .child + .child
  • 什么...你是对的,向父级添加溢出:隐藏会使浮动的 div 再次被父级 div 包含。这是令人难以置信的反直觉......
  • 会不会有一个不使用溢出的替代方案:隐藏?不幸的是,在实际项目中我想要这个,因为我有一个 position:relative div,它与现在被切断的父级重叠。
  • 我想出了一个不用overflow的方法。我只需要将 display:table 添加到父级。
猜你喜欢
  • 1970-01-01
  • 2019-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-18
  • 1970-01-01
  • 2018-05-02
  • 1970-01-01
相关资源
最近更新 更多