【问题标题】:two divs, one next to each other, in the same corner两个 div,一个相邻,在同一个角落
【发布时间】:2019-09-28 09:28:32
【问题描述】:

请问如何将两个 div 并排放置在同一个角落?例如,这是我到目前为止所拥有的(参见 sn-p)。我想要另一个 div,比如说左上角的蓝色,旁边是现有的红色。是不是也可以放在红色下面?

谢谢

<!DOCTYPE html>
<html>

<head>
    <meta charset='utf-8'>
</head>

<style>
    .box {
        position: absolute;
        background-color: red;
        width: 100px;
        height: 100px;
    }

    .box.top {
        top: 0;
    }

    .box.right {
        right: 0;
    }

    .box.left {
        left: 0;
    }

    .box.bottom {
        bottom: 0
    }
</style>

<body>

<div id="container">

    <div id="main" style="background-color: pink; height: 100vh; width: 100%; position: relative;"></div>
    <div class="box top left"></div>
    <div class="box top right"></div>
    <div class="box bottom left"></div>
    <div class="box bottom right"></div>
</div>

</body>

</html>

【问题讨论】:

  • 如果你想在左上角的红框之后使用left: 100px,或者如果你想在下面使用top:100px(虽然你的屏幕必须至少有300px高),请使用left: 100px - 请阅读:developer.mozilla.org/en-US/docs/Web/CSS/position
  • 是的,这很公平,但是请不要硬设置就可以做到吗?
  • 不带绝对定位
  • 如果需要绝对定位,可以用javascript检测其中一个框的位置,将另一个放在旁边
  • 您可能想看看 flex 或 grid 方法:stackoverflow.com/questions/45925949/…

标签: html


【解决方案1】:

考虑为所有四个角元素创建包装 div,而不是定位框本身。因此,您将拥有以下内容,而不是拥有四个盒子 div:

<div class="box-wrapper top left">
  <div class="box red"></div>
  <div class="box blue"></div>
</div>
<div class="box-wrapper top right">
  <div class="box red"></div>
</div>
<div class="box-wrapper bottom left">
  <div class="box red"></div>
</div>
<div class="box-wrapper bottom right">
  <div class="box red"></div>
</div>

现在,将display: flex 用于box-wrapper 类和flex-direction: row,以便元素水平对齐。 (您可以根据需要分配不同的类并配置“每个角”的方向)。

这是一个显示您提到的案例的工作示例(在左上角的红色框旁边有一个蓝色框):https://jsfiddle.net/uejw2yr3/(如果您想要下面的框,请将flex-direction: row 替换为@ 987654328@)

如果您想了解更多关于 flexbox 的信息(试试看,它很棒)请查看:https://css-tricks.com/snippets/css/a-guide-to-flexbox/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-02
    • 2011-05-14
    • 2013-04-20
    • 1970-01-01
    • 2020-07-30
    • 2012-02-12
    • 2019-07-20
    相关资源
    最近更新 更多