为什么此文本未与我的CSS网格行垂直对齐?

我的网站上将提供有关温度的信息,我希望读出温度,后跟一个度数符号以及“ C”或“ F”。页面上还有关于天气的其他信息,因此我正在使用CSS网格来布局页面并将所有部分分解。当我将度数注释字体大小减小时,度数在页面上移得更高。我希望它与温度值保持一致,但是我无法弄清页面中发生了什么。任何帮助都将是惊人的。

有问题的文字图片:

为什么此文本未与我的CSS网格行垂直对齐?

.wrapper {
  display: grid;
  grid-template-rows: 200px 100px;
  padding-bottom: 2.5em;
}

.temp {
  display: grid;
  grid-template-columns: 150px 150px;
  padding: none;
  font-size: 3em;
  align-content: center;
  justify-content: center;
}

.degree-note {
  font-size: 30px;
  align-content: center;
}
<div class="wrapper">
  <img class='loading-text' src='img/weather-app-loading.png'>

  <div class='temp'>
    <h2 class='temp-degree'>34</h2>
    <h2 class='degree-note'>&deg C</h2>
  </div>
</div>

zhang20045237 回答:为什么此文本未与我的CSS网格行垂直对齐?

改为使用 CSS flex-box 。 它比CSS网格更加灵活,响应速度更快。 只需运行您将看到的代码段即可。

await
.wrapper {
  display: flex;
  flex-direction: column;
  padding-bottom: 2.5em;
}

.temp {
  align-items: center;
  display: flex;
  font-size: 3em;
  padding: none;
}

.temp-symbol {
  align-self: flex-start;
  font-size: 30px;
}

,

H2标签将换行。而是使用span标签为文本添加特定的类。

.wrapper {
    display:grid;
    grid-template-rows: 200px 100px;
    padding-bottom: 2.5em;
}
.temp{ 
    position: relative;
    display:grid;
    grid-template-columns: 150px 150px;
    padding: none;
    font-size: 3em;
    align-content: center;
    justify-content: center;
}

.degree-note {
    position: absolute;
    top: 1rem;
    font-size: 30px;
    align-content: center;
    }
<div class="wrapper">
      <img class='loading-text' src='img/weather-app-loading.png'></img>

      <div class='temp'>
        <h2>
        <span class='temp-degree'>34</span>
        <span class='degree-note'>&deg C</span>
        </h2>
      </div>
    </div>

,

标题通常带有默认边距。从h2元素中删除这些边距。那应该可以带你去哪里。

然后,为了更加精确,请为内容设置相等的行高。

将此添加到您的代码中:

.temp {
  line-height: 1;      /* inherits to children */
}

.temp-degree {
  margin: 0;           /* remove default margin */
  text-align: right;   /* optional; eliminates gap between elements */
}

.degree-note {
  margin: 0;           /* remove default margin */
}

enter image description here

.wrapper {
  display: grid;
  grid-template-rows: 200px 100px;
  padding-bottom: 2.5em;
}

.temp {
  display: grid;
  grid-template-columns: 150px 150px;
  font-size: 3em;
  align-content: center;
  justify-content: center;
  line-height: 1; /* inherits to children */
}

.temp-degree {
  margin: 0; /* remove default margin */
  text-align: right;
}

.degree-note {
  font-size: 30px;
  margin: 0; /* remove default margin */
}
<div class="wrapper">
  <img class='loading-text' src='img/weather-app-loading.png'>
  <div class='temp'>
    <h2 class='temp-degree'>34</h2>
    <h2 class='degree-note'>&deg C</h2>
  </div>
</div>

本文链接:https://www.f2er.com/3131605.html

大家都在问