首页 > 解决方案 > 使用 flexbox 在标题中定位 h1、h2 和 2 个图像

问题描述

我正在尝试使用 html/css 为我的网站创建标题。这是我到目前为止所取得的成就:

标题

该照片显示了整个标题元素,没有任何部分被切断。我试图让图像和 h1 和 h2 居中,h1 和 h2 在图像之间垂直居中。此外,我希望 h2 比它更靠近 h1 下方。这是我当前的 html/css:

* {
  box-sizing: border-box;
}

html {
  height: 100%;
  font: 16px Geneva, Verdana, Helvetica, sans-serif;
}

body {
  margin: 0px;
  padding: 0px;
  max-width: 1000px;
  color: #0D1B1E;
}

body > header {
  display: flex;
  flex-flow: row nowrap;
  margin: 0 auto;
  background-color: #FAF9F4;
  height: 100%;
}

.first {
  padding: 5px;
  flex: 1;
}

.second {
  padding: 5px;
  flex: 3;
}

.third {
  padding: 5px;
  flex: 1;
}
<header>
      <div class="first">
        <img src="images/header-logo1.png" alt="Law Enforcement   Badge Logo" width="100" height="100">
      </div>
      
      <div class="second">
        <h1>On Scene Academy</h1>
        <h2>law enforcement training and tactics</h2>
      </div>
      
      <div class="third">
         <img src="images/header-logo2.png" alt="Law Enforcement Badge Logo" width="100" height="100">
      </div>
    </header>

任何帮助将不胜感激!我也愿意使用除 flexbox 之外的任何其他显示或定位方法。谢谢!

标签: htmlcssflexbox

解决方案


这是解决方案。您需要在标题标签中使用 flex 并添加“align-items:center”属性以使其居中。如下;-

* {
  box-sizing: border-box;
}

html {
  height: 100%;
  font: 16px Geneva, Verdana, Helvetica, sans-serif;
}
h1,h2{margin:0;}
body {
  margin: 0px;
  padding: 0px;
  max-width: 1000px;
  color: #0D1B1E;
}

body > header {
  display: flex;
  flex-flow: row nowrap;
  margin: 0 auto;
  background-color: #FAF9F4;
  height: 100%;
}
header{align-items:center;}

.first {
  padding: 5px;
  flex: 1;
}

.second {
  padding: 5px;
  flex: 3;
}

.third {
  padding: 5px;
  flex: 1;
}
<header>
      <div class="first">
        <img src="images/header-logo1.png" alt="Law Enforcement   Badge Logo" width="100" height="100">
      </div>
      
      <div class="second">
        <h1>On Scene Academy</h1>
        <h2>law enforcement training and tactics</h2>
      </div>
      
      <div class="third">
         <img src="images/header-logo2.png" alt="Law Enforcement Badge Logo" width="100" height="100">
      </div>
    </header>


推荐阅读