html - 如何让这些 div 在页面中央相互堆叠?

标签 html css

我还是不太明白如何使 div 居中。在这个 fiddle 中,您可以看到我已将 div 居中,但它们是重叠的。我已将两者都设置为显示可以解决问题的内联 block 思维,但这并没有做任何事情。

https://jsfiddle.net/fyu1sup0/1/

html, body {
  font-family:;
  margin:0 auto;
  text-transform: lowercase;
  font-family: Europa;
  letter-spacing: 0.5px;
}

.container {
  padding:0;
  margin:0 auto;
}

.top {
  background-color: blue;
  position: absolute;
  width: 300px;
  height: 200px;
  z-index: 15;
  top: 50%;
  left: 50%;
  margin: -100px 0 0 -150px;
  display:inline-block;
}
.top h1 {
  width:100%;
  font-size:50px;
  color:#2CCDAD;
}

.bottom {
  position: absolute;
  width: 300px;
  height: 200px;
  z-index: 15;
  top: 50%;
  left: 50%;
  margin: -100px 0 0 -150px;
  display:inline-block;
}
.bottom h1 {
  font-size:40px;
  color:black;
  width:100%;
}

最佳答案

您将需要使用包装器元素。然后使用transform: translateY(-50%)将wrapper的位置调整到页面的中心。

参见 https://jsfiddle.net/Labo59nx/

html, body {
  font-family:;
  margin:0 auto;
  text-transform: lowercase;
  font-family: Europa;
  letter-spacing: 0.5px;
}

.wrapper {
  position: absolute;
  width:300px;
  top: 50%;
  left: 50%;
  margin: 0 0 0 -150px;
  transform: translateY(-50%);
}

.container {
  padding:0;
  margin:0 auto;
}

.top {
  background-color: blue;
  width: 300px;
  height: 200px;
  z-index: 15;
  display:inline-block;
}
.top h1 {
  width:100%;
  font-size:50px;
  color:#2CCDAD;
}

.bottom {
  background-color:red;
  width: 300px;
  height: 200px;
  z-index: 15;
  display:inline-block;
}
.bottom h1 {
  font-size:40px;
  color:black;
  width:100%;
}
<body>

    <div class="wrapper">
    
      <div class = "top">
        <div class="container">
        <h1>header</h1>
        </div>
      </div>

      <div class = "bottom">
        <div class="container">
        <h1>text</h1>
        </div>
      </div>
    
    </div>


</body>

关于html - 如何让这些 div 在页面中央相互堆叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46174981/

相关文章:

javascript - 尝试加载第一张图像时 FlexSlider 图像失真/跳跃?

php - SoundCloud 如何让 favicon 在按下播放按钮时动态变化?

html - 居中时仅在最后一行文本下划线

html - 如何在网站中使用自定义字体

css - 如何使图像充当视频叠加层?

javascript - 下拉菜单的问题

java - 在 html 中嵌入 Dygraph

jquery - 居中 bxslider jquery 插件

html - 将引导下拉背景更改为只是一个图像

css - Extjs 消息框居中对齐