尝试将中心标题添加到我的页面

Trying to add a center title to my page

我想在我的页面中间添加一个中心文本标题,但它不会显示。代码似乎正确,没有发现错误。

<div id="welcome_text_div">
  <p id="welcome_text"> Welcome </p>
</div>


#welcome_text_div {
position: absolute;
background-color:red;
width:800px;
height:300px;
top: 50%;
margin-top: -150%;
left: 50%;
margin-left: -400px;

}

#welcome_text {
color: white;
font-family: sans-serif;
text-transform: uppercase;
font-weight: bold;
font-size: 55px;
text-align: center;

}

试试这个

  #welcome_text_div {
    position: absolute;
    background-color:red;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    }
    
    #welcome_text {
    color: white;
    font-family: sans-serif;
    text-transform: uppercase;
    font-weight: bold;
    font-size: 55px;
    text-align: center;
    width: 800px;
    line-height: 300px;
    }
    <div id="welcome_text_div">
      <p id="welcome_text"> Welcome </p>
    </div>
    
    
  

<div id="welcome_text_div">
   <p id="welcome_text"> Welcome </p>
</div>


#welcome_text_div {
position: absolute;
background-color:red;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}

#welcome_text {
color: white;
font-family: sans-serif;
text-transform: uppercase;
font-weight: bold;
font-size: 55px;
text-align: center;
width: 800px;
line-height: 300px;
}

你可以用 flexbox 来实现。

您需要对容器做的就是定义它的宽度和高度(并给它一个背景颜色):

#welcome_text_div {
    background-color:red;
    width:800px;
    height:300px;
}

然后添加这三行来设置 flexbox 显示上下文,并将其垂直和水平居中:

display:flex;
align-items:center;
justify-content:center;

然后从内部 div 中删除所有额外的格式。

#welcome_text_div {
    background-color:red;
    width:800px;
    height:300px;
    display:flex;
    align-items:center;
    justify-content:center;
}

#welcome_text {
    color: white;
    font-family: sans-serif;
    text-transform: uppercase;
    font-weight: bold;
    font-size: 55px;
}

https://jsfiddle.net/k5zve6bf/

您只需要使用 text-align: center 它应该会自动居中。顺便说一句,我看到您经常使用 ID,这是非常糟糕的做法。 ID 应该用于 javasscript 选择器,而 class 用于 css。

.center-text {
  text-align:center;
}

.title-text {
  // Do css formating here  
}
 <div class="center-text title-text">
  <p class="page-title"> Welcome </p>
</div>