如何在 HTML 中将文本向右对齐并垂直居中?

问题描述 投票:0回答:2

我正在学习 HTML 和 CSS,并通过为个人页面编写一些 HTML 进行练习。我首先创建一个标题,其中我的名字向右对齐,但文本与顶部垂直对齐。我见过一些人试图实现类似目标的例子,但似乎没有一个能够解决我的问题,或者提供一个看起来比我想要做的复杂得多的解决方案(对齐 x 和 x 上的文本) y 轴独立)

.header1 {
  background-color: #000000;
  border: none;
  height: 40px;
  top: 0px;
  left: 0px;
  width: 100%;

}
.margin-zero {
  margin: 0px;
}
.header1Title {
  color: white;
  font-size: 25px;
  height: 40px;
  text-align: right;
  vertical-align: middle;
}
<header class="header1 margin-zero">
  <h1 class="header1Title margin-zero">Luis Argueta</h1>
</header>

html css
2个回答
0
投票

要右对齐,您可以使用 justify-content: flex-end;并使其真正居中使用 align-items: center;

.header1 {
    background-color: #000000;
    border: none;
    height: 40px;
    /* top: 0px; */
    /* left: 0px; */
    width: 100%;

    /* added styles */
    align-items: center;
    display: flex;
    justify-content: flex-end;
}

.header1Title {
    color: white;
    font-size: 25px;
    /* height: 40px; 
    text-align: right;
    vertical-align: middle; */
}

0
投票

如果你刚刚开始学习 HTML 和 CSS,我建议学习 flex 属性。这是垂直对齐元素的最简单方法。 在父元素

.header1
中添加
display: flex;
以将容器设置为 Flexbox。
align-items: center;
将垂直对齐子元素,
justify-content: end;
将其发送到父容器的末尾。

.header1 {
  background-color: #000000;
  border: none;
  height: 40px;
  top: 0px;
  left: 0px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: end;
}

.margin-zero {
  margin: 0px;
}


.header1Title {
  color: white;
  font-size: 25px;
}
<header class="header1 margin-zero">
  <h1 class="header1Title margin-zero">Luis Argueta</h1>
</header>

© www.soinside.com 2019 - 2024. All rights reserved.