【问题标题】:How to position divs using Relative and Absolute positioning如何使用相对和绝对定位来定位 div
【发布时间】:2020-09-28 18:41:44
【问题描述】:

我希望我的显示器看起来像这样。

但是,它看起来像这样

我的代码是这样的。

HTML

 <body>
  <div class="top">
    <div class="left">
      <h1>TOP LEFT</h1>
    </div>
    <div class="right">
      <h1>TOP RIGHT</h1>
    </div>
  </div>
  <div class="bottom">
    <h1>BOTTOM</h1>
  </div>
</body>

CSS

body{
  text-align:center
}

.top{
  position:relative;
}

.left{
  position:absolute;
  width:50%;
}

.right{
  position:absolute;
  width:50%;
  left:50%;
}

.bottom{
  position:relative;
}

我应该对我的代码进行哪些必要的更改。我想保持动态,而不是指定 div 的高度(以像素为单位)。

【问题讨论】:

  • margin-toppadding-top on .bottom 将其向下推?
  • @RamondeVries — 这与以像素为单位指定高度本质上是相同的问题。
  • 使用弹性盒子。 Demo
  • 欢迎来到 Stack Overflow!绝对定位是一种非常糟糕的网页布局方法。它非常不灵活,并且有更好、响应速度更快的选项。查看LearnLayout.com

标签: html css layout css-selectors


【解决方案1】:

不要。定位不适合这种布局。

为工作使用正确的工具。使用 flexbox 将两个元素并排放置,让正常流程处理其余部分。

h1 {
  text-align: center;
}

.top {
  display: flex;
}

.top>div {
  flex: 0 0 50%;
}
<div class="top">
  <div class="left">
    <h1>TOP LEFT</h1>
  </div>
  <div class="right">
    <h1>TOP RIGHT</h1>
  </div>
</div>
<div class="bottom">
  <h1>BOTTOM</h1>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多