首页 > 解决方案 > CSS 错误:为什么页眉水平对齐和页脚不均匀对齐?

问题描述

我是一个编码新手 - 使用 CSS flex box 创建一个模拟响应式布局,我在水平对齐最宽视口中的页眉元素以及将页脚均匀地弯曲到空间时遇到了麻烦。

对于标题,我尝试过display:inlinetext-align:center没有成功。使用页脚,我尝试过display:flex,但justify-content: space-evenly也没有成功。

<html>
 <body>
  <header>
    <div class="logo">
       <h1>actual image logo here</h1>
       <h1>The ABC Company</h1>
    </div>
    </header>
  <footer>
    <ul class="social">
      <li class="social_icon">Twitter Logo here</li>
      <li class="social_icon">Facebook logo here</i></li>
      <li class="social_icon">Insta logo here</li>
    </ul>
  </footer>
 </body>
</html>

标签: htmlcssalignment

解决方案


如果您的页眉和页脚占屏幕宽度的 100%,则执行以下操作:

header,footer {
    width:100%
}

然后对齐任何元素的中心,这里最简单的方法是使用弹性框,就像你想的那样

header {
     background: #aaf;
     display: flex;
     justify-content: center;
   }

footer {
     background: #aff;
     display: flex;
     justify-content: center;
    }

header div.logo {
       display: flex;
       justify-content: center;
    }

footer ul.social {
      width : 100%;
      list-style: none;
      display: flex;
      justify-content: space-evenly;
    }

由于 Header 和 Footer 每个都有一个子项(一个 div 代表页眉,一个 ul 代表页脚),您需要再次使用 flex 将这些子项(h1 和 li)的内容居中。
为了在space-evenly上面工作,ul我必须增加它的默认宽度,否则它看起来fit content会居中。
如果您有任何问题,请随时发表评论。

body {
  background: rgb(36, 36, 33);
  margin: 0;
  padding: 0;
  height: 100vh;
}

   header,
   footer {
     width: 100%
   }

   header {
     background: #aaf;
     display: flex;
     justify-content: center;
   }

    footer {
     background: #aff;
     display: flex;
     justify-content: center;
    }

    header div.logo {
       display: flex;
       justify-content: center;
    }

     header div.logo > *{
       padding: 0 10px;
     }

    footer ul.social {
      width : 100%;
      list-style: none;
      display: flex;
      justify-content: space-evenly;
    }
<!Doctype HTML>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
     <link rel="stylesheet" href="style.css">
    <title></title>
</head>

<body>
  <header>
      <div class="logo">
          <h1>actual image logo here</h1>
          <h1>The ABC Company</h1>
      </div>
  </header>
  <footer>
      <ul class="social">
          <li class="social_icon">Twitter Logo here</li>
          <li class="social_icon">Facebook logo here</i></li>
          <li class="social_icon">Insta logo here</li>
      </ul>
  </footer>
</body>

</html>


推荐阅读