为什么文本在移动设备中不居中 (HTML)

Why the text is not centered in mobile devices (HTML)

Website screenshot in PC

Website screenshot in the mobile device

这是HTML代码

<!DOCTYPE html>
<html lang="en">
<head>
  <link href="https://fonts.googleapis.com/css2?family=PT+Sans+Narrow:wght@700&display=swap" rel="stylesheet"
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href = "boi.css">
</head>
<body>
  <div class="first">
    <h1>Hey!</h1>
</div>
</body>
</html>>

这是 CSS 代码

body {
background-color: rgb(20, 18, 18);
}
.first {
    position: relative;
    margin-right: 300px;
    color: white;
        text-align: center;        
        font-family: 'PT Sans Narrow', sans-serif;
}

使用以下css

.first
{
   color: white;
   text-align: center;
}
.first h1
{
   display: inline-block;
}

嘿,有很多解决办法。

  1. 您可以像下面的代码一样设置元素的宽度。
  2. 或者您可以将 display: 选项设置到元素中(例如,display:contents

body {
background-color: rgb(20, 18, 18);
}
.first {
    position: relative;
    margin-right: 300px;
    color: white;
    text-align: center;        
    font-family: 'PT Sans Narrow', sans-serif;
    width: 100%;
    /* display: contents; */
}
<link href="https://fonts.googleapis.com/css2?family=PT+Sans+Narrow:wght@700&display=swap" rel="stylesheet"
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href = "boi.css">
<body>
  <div class="first">
    <h1>Hey!</h1>

您可以使用 flexbox,尤其是在移动尺寸或桌面尺寸的媒体查询中

.first {
    position: relative;
    margin-right: 300px;
    color: white;
    width:100%;
       display:flex;
justify-content:center;
align-items:center;
        text-align: center;        
        font-family: 'PT Sans Narrow', sans-serif;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <link href="https://fonts.googleapis.com/css2?family=PT+Sans+Narrow:wght@700&display=swap" rel="stylesheet">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href = "boi.css">
</head>
<body>
  <div class="first">
    <h1>Hey!</h1>
</div>
</body>
</html>

我认为您只需要删除 margin-right: 300px; - 这最终会将所有内容向左移动 300px,从而使其在移动设备上非常 off-center。