首页 > 解决方案 > 为什么我的 H1 标题子级会覆盖我的 div 父级维度?为什么我不能正确操作 h1?

问题描述

我正在尝试在导航栏下方的网页中间制作一个页面标题标题,然后我试图使标题边框围绕标题的文本环绕,这样就没有很多填充左和右。

我能够使标题居中,我能够更改标题的字体、装饰等,但我无法弄清楚为什么在标题本身不改变其位置的情况下无法操纵标题的宽度。

我尝试在父 div 和标题子项中更改 CSS 代码,但无济于事,我尝试的任何方法似乎都不起作用。

我检查了控制台,看看我写的一些代码是否没有影响我的元素,但控制台显示代码正在影响它们。

请告诉我我在哪里犯了错误......

.title {
  position: relative;
}

.title h1 {
  display: flex;
  justify-content: center;
  position: static;
  font-family: 'Prompt', sans-serif;
  font-size: 40px;
  color: white;
  background-color: black;
  border: 3px solid yellow;
  border-radius: 10px;
}
<div class="title">
  <h1>LOCATIONS</h1>
</div>

这是使标题居中的代码,不会弄乱我页面上标题的位置。

标签: htmlcssflexbox

解决方案


flex属性移动到子容器(以这种方式在divh1中居中)并为其定义 100% 宽度:title

如果您想要文本及其边框(顶部、左侧、右侧)周围有一些(黑色)空间,请使用paddingh1类似于我在下面所做的

.title {
  display: flex;
  justify-content: center;
  width: 100%;
}

.title h1 {
    font-family: 'Prompt', sans-serif;
  font-size: 40px;
  color: white;
  background-color: black;
  border: 3px solid yellow;
  border-radius: 10px;
  padding: 6px 4px 0;
}
<div class="title">
  <h1>LOCATIONS</h1>
</div>


推荐阅读