首页 > 解决方案 > 如何正确地将文本和图像与 flexbox 居中?

问题描述

我试图将“旅游博客;查看项目”与图像居中,因此文本位于左侧图像的中间。不重叠

我尝试使用 flexbox 网格,但我不知道现在该做什么

html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Fabian Gmeindl</title>
    <link rel="stylesheet" type="text/css" href="css/master.css">
  </head>
  <body>
    <header id="showcase">
      <div class="Top-Page">

      <h1>HEY,</h1>
      <h2>I'm Fabian Gmeindl</h2>
      <p>Skier, Writer, Entrepreneur</p>

      </div>
    </header>
      <div id="project-home">



      <!-- Top Page -->

      <!-- Page Projects -->
      <div class="rtro-area" class="wrapper">




        <h2>Travel Blog</h2>
        <a href="https://www.rtrobrand.com">View Project</a>
        </div>
        <img  class="img-rtro" class="wrapper" src="Resources/rtro-toppage.png" alt="Rtro Blog Top Page">


        <footer id="main footer">
          <p>Copyright &copy; 2019 Fabian Gmeindl</p>
        </footer>

      </div>
  </body>
</html>

的CSS

*{
  margin: 0;
  padding: 0;
  border:0;

}


h1{
  color:#56A1B1;
  font-size: 100px;
  font-weight: bold;

}

#showcase h2{
  color:white;
  font-size: 80px;
  text-transform: uppercase;
}

p{
  color:white;
}

.Top-Page{
  padding-left: 8%;
}
body{
  background-color: #f4f4f4;
  line-height: 1;

}


#showcase{
  background-image: url('../Resources/Portrait.jpg');
  background-size: cover;
  background-position: center;
  height: 100vh;
  display:flex;
  flex-direction: column;
  justify-content: center;
  align-content: center;
}



/* Project Home Page */




.img-rtro{
  width: 1300px;
  float: right;
  margin-left: 20%;

}

#project-home{
background-image: url('../Resources/background.jpg');
background-size: cover;
background-position: center;
height: 100vh;
display:flex;
flex-direction: column;
justify-content: center;
}

当我向下滚动到问题所在的第二部分时,它看起来像这样 https://imgur.com/mt2HStK

标签: htmlcss

解决方案


如果将align-items: center添加到 flexcontainer 的 CSS,则可以对齐“Travel Blog;View Project”部分。(align-items — 控制所有项目在交叉轴上的对齐方式。)您必须在交叉轴上居中,因为您正在使用“flex-direction: column”。

一般来说,为了使元素与 flexbox 对齐,我可以推荐这篇文章:https ://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container


推荐阅读