html - 仅居中 div 中的两个元素之一?

标签 html css flexbox centering

<分区>

我有一个简单的网页,其中包含一个 .topnav 栏和一个包含一些元素的 .container。我试图在页面的 body 中仅将 .container 居中,而不是 .topnav,以便它垂直居中。但是,当我尝试使用以下样式设置 body 时:

display:flex;
align-items:center;
justify-content:center;

.topbar.container 都居中。如何让 .container 垂直居中?

body,
html {
  height: 100%;
}

.contact_box {
  text-align: center;
  background-color: red;
  border: 1px solid #c0c0c0;
  border-radius: 5px;
  height: 20em;
  width: 25em;
  box-shadow: 1px 1px 6px #757677;
  float: left;
}

.contact_box img {
  margin-top: 3.3em;
  margin-bottom: 1.2em;
  height: 3em;
  width: 3em;
}

.contact_box h3 {
  color: #6d6d6d;
}

#contact .container {
  display: flex;
  align-items: center;
  justify-content: center;
}
<body id="contact">
  <div class="topnav" id="myTopnav">
    <a href="index.html">Home</a>
    <a href="about.html">About</a>
    <a href="#" class="selected">Contact</a>
    <a class="icon" onclick="myFunction()">&#9776;</a>
  </div>

  <div class="container">
    <div class="row" id="contact_section">
      <div class="contact_box" class="col-md-4">
        <a href="https://github.com/" target="_blank"><img src="resources/github_logo.png" alt="Github"></a>
        <br>
        <h3>GitHub</h3>
      </div>

      <div class="contact_box" class="col-md-4">
        <a href="https://www.linkedin.com" target="_blank"><img src="resources/linkedin_logo.png" alt="LinkedIn"></a>
        <h3>LinkedIn</h3>
      </div>

      <div class="contact_box" class="col-md-4">
        <img src="resources/email_icon.png" alt="EMAIL">
        <h3>Email</h3>
      </div>
    </div>
  </div>
</body>

现在是这样的:

enter image description here

最佳答案

你好让它在页面中间垂直对齐,设置容器的高度为视口(viewport)的100%:

#contact .container {
    height:100vh;
    display:flex;
    align-items:center;
    justify-content:center;
}

关于html - 仅居中 div 中的两个元素之一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46856330/

相关文章:

css - 如何使用 CSS flexbox 垂直对齐和拉伸(stretch)内容

javascript - 如何在 HTML 中使我的列动态化

html - 无法找到填充的原因 - CSS

html - CSS 背景图像仅跨度 960px

javascript - 带有子菜单的可折叠垂直侧边栏菜单图标

javascript - React Native 中的 Flex 框不起作用按钮不会显示

html - 固定标题 Flex 表 - 标题垂直对齐

html - 使用 CSS 将图像水平居中

javascript - 使用 parseFloat 使用 JavaScript 获取字符串中的价格,但 parseInt 无法正常工作

css - 用 CSS 模仿 HBox/VBox