html - 如何将一个元素放在其他元素之上

标签 html css

我想将一个元素放在另一个元素之上而不修改第二个元素的位置。我的意思是:

.container {
	display: flex;
	align-content: baseline;
	padding: 50px;
	width: 50px;
	height: 50px;
	background-color: blue;
}

.base {
  color: black;
}

.top {
  color: red;
}
<div class="container">
  <div class="base">
    base
    <div class="top">
      should be on top
    </div>
  </div>
</div>

我希望 should be on top div 放置在 base div 之上,并且 base div 仍然对齐确实如此。我试过使用相对定位并给出负底值,但它没有那么灵敏。这就是我希望它们成为的样子,除了 base 应该保持以前的位置:

    .container {
    	display: flex;
    	align-content: baseline;
    	padding: 50px;
    	width: 50px;
    	height: 50px;
    	background-color: blue;
    }

    .base {
      color: black;
    }

    .top {
      color: red;
    }
<div class="container">
  <div class="top">
    should be on top
    <div class="base">
      base
    </div>
  </div>
</div>

should be ontop div 必须在 base 之上,而 base 则位于之前的位置。我该怎么做?
这就是我正在尝试的:

    .container {
    	display: flex;
    	align-content: baseline;
    	padding: 50px;
    	width: 50px;
    	height: 50px;
    	background-color: blue;
    }

    .base {
      color: black;
    }

    .top {
      position: relative;
      color: red;
      bottom: 4.8em;
    }
    <div class="container">
      <div class="base">
        base
        <div class="top">
          should be on top
        </div>
      </div>
    </div>
这就是我希望它们放置的方式。但是,如果 should be ontop div 的行数发生变化,那么它会溢出到 base div 之上。我认为它可以使用 js 来完成,但我更喜欢它只使用 css。有办法吗?

最佳答案

看来我误解了这个问题。我已经更新了答案以反射(reflect)这些变化。

父级 div 的位置必须是 relative,内部 div 的位置必须是 absolute。所以 above div 成为相对于 base div 的“绝对”。

现在您需要指定 div 需要“高于”多少,因为没有其他方法可以从流中删除元素并将其定位到其他位置。 (除非你使用的是 javascript)

您的代码可能如下所示:

.container {
	display: flex;
	align-content: baseline;
	padding: 50px;
	width: 50px;
	height: 50px;
	background-color: blue;
}

.base {
  position: relative;
  color: black;
}

.above {
  position: absolute;
  top: -60px;
  color: red;
}
<div class="container">
  <div class="base">
    base
    <div class="above">
      should be above
    </div>
  </div>
</div>

关于html - 如何将一个元素放在其他元素之上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47721343/

相关文章:

javascript - 使用 Jquery 获取多个 div 的 HTML

css - 在 div 中垂直居中文本

jquery - 通过单击指向 iframe 中的内部链接的链接向下滚动整个页面

html - css 图像链接在悬停时更改不透明度

javascript - jquery 获取窗口位置 + 滚动 - 但如果不滚动则不显示

html - 按钮中的 Shadow DOM

html - 显示替代文字时的 img 大小

javascript - 如何获取特定div的父级?

css - SASS计算网格的列宽

jQuery 事件 - 元素变得可见