如何使用 CSS 将两个或多个元素堆叠到右侧

How to Stack two or more Elements to the Right hand side using CSS

我想让我的页眉元素相互堆叠到屏幕的右侧(H1 元素和 H2 元素就在它下面)。我刚刚开始掌握 CSS 的窍门,所以请多多包涵。尝试在线搜索解决方案,但只能在只有一个元素时找到答案。

无论如何,这就是页面现在在屏幕上的样子:

蓝色"We Help People and Businesses"是H1元素。白色的"Achieve today's Goals and tomorrow's Aspirations"是H2元素。这两个 Header 元素都嵌套在 DIV

目前 CSS 代码如下所示:

.hero01_content-div {
  margin-top: 400px;
}

.hero01_content-head-test-main {
  position: relative;
  width: 600px;
  margin-top: 0px;
  margin-bottom: 0px;
  padding: 5px 15px;
  float: right;
  background-color: #0080c7;
  font-family: Lato, sans-serif;
  color: white;
  text-align: right;
}

.hero01_content-subhead-test-main {
  position: relative;
  width: 500px;
  margin-top: 0px;
  margin-bottom: 0px;
  padding: 10px 15px;
  float: right;
  background-color: white;
  font-family: Lato, sans-serif;
  color: #ec008c;
  text-align: right;
}

如何使 H2 元素堆叠在 H1 元素的正下方,同时这两个元素都在右侧?我将不胜感激任何帮助。提前谢谢你。

可在此处找到演示上述内容的代码笔:http://codepen.io/anon/pen/qOoVxb

您需要将 float: right 设置为 parent 容器并从标题元素中移除浮动属性,因为它会脱离正常流。

Codepen Demo

.hero01_content-div {
  margin-top: 400px;
  float: right; /* Added */
}
.hero01_content-head-test-main {
  position: relative;
  width: 600px;
  margin-top: 0px;
  margin-bottom: 0px;
  padding: 5px 15px;
  background-color: #0080c7;
  font-family: Lato, sans-serif;
  color: white;
  text-align: right;
}
.hero01_content-subhead-test-main {
  position: relative;
  width: 500px;
  margin-top: 0px;
  margin-bottom: 0px;
  padding: 10px 15px;
  float: right;
  background-color: white;
  font-family: Lato, sans-serif;
  color: #ec008c;
  text-align: right;
}
<div class="w-section hero-01">
  <div class="hero01_overlay">
    <div class="w-container hero01_content">
      <div class="w-clearfix hero01_content-div hero01_test" data-ix="scroll-reveal">
        <h1 class="hero01_content-head-test-main">We Help People and Businesses</h1>
        <h2 class="hero01_content-subhead-test-main">Achieve today's Goals and tomorrow's Aspirations</h2>
      </div>
    </div>
  </div>
</div>

好的,您需要删除

.hero01_content-div {
margin-top: 400px;
float: right;
}

然后改变这些

.hero01_content-head-test-main {
postion: absolute;
top: 0px;
width: 600px;
margin-top: 0px;
margin-bottom: 0px;
padding: 5px 15px;
float: right;
background-color: #0080c7;
font-family: Lato, sans-serif;
color: white;
text-align: right;
}

.hero01_content-subhead-test-main {
float: right;
width: 500px;
margin-top: 0px;
margin-bottom: 0px;
padding: 10px 15px;
background-color: white;
font-family: Lato, sans-serif;
color: #ec008c;
text-align: right;
}