如何在flexbox中居中文本?

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

为什么文本不在下面的代码的中心? (标题和标记行)。

应该是这样的,

body {
  margin: 0;
  padding: 0;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: #000;
}

p {
  position: relative;
  font-family: sans-serif;
  text-transform: uppercase;
  font-size: 2em;
  letter-spacing: 4px;
  overflow: hidden;
  background: linear-gradient(90deg, #000, #000fe6, #000);
  background-repeat: no-repeat;
  background-size: 80%;
  animation: animate 3.75s linear infinite;
  -webkit-background-clip: text;
  -webkit-text-fill-color: rgba(45, 45, 45, .05);
}

@keyframes animate {
  0% {
    background-position: -500%;
  }
  100% {
    background-position: 500%;
  }
}
<body>
  <div>
    <p>Title</p>
    <p>Tag Line</p>
  </div>
</body>

为什么文本不在上面的代码的中心? (标题和标记行)

应该是这样的,

html css flexbox center
3个回答
3
投票

在你的p中使用它

 margin:0 auto;
  display:block;
  text-align:center;

body {
  margin: 0;
  padding: 0;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: #000;
}

p {
  position: relative;
  font-family: sans-serif;
  text-transform: uppercase;
  margin:0 auto;
  display:block;
  text-align:center;
  font-size: 2em;
  letter-spacing: 4px;
  overflow: hidden;
  background: linear-gradient(90deg, #000, #000fe6, #000);
  background-repeat: no-repeat;
  background-size: 80%;
  animation: animate 3.75s linear infinite;
  -webkit-background-clip: text;
  -webkit-text-fill-color: rgba(45, 45, 45, .05);
}

@keyframes animate {
  0% {
    background-position: -500%;
  }
  100% {
    background-position: 500%;
  }
}
<body>
  <div>
    <p>Title</p>
    <p>Tag Line</p>
  </div>
</body>

1
投票

你也必须调整p的内容。您可以使用text-align:center或display:flex + justify-content:center

body {
  margin: 0;
  padding: 0;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: #000;
}

p {
  position: relative;
  font-family: sans-serif;
  text-transform: uppercase;
  font-size: 2em;
  letter-spacing: 4px;
  overflow: hidden;
  background: linear-gradient(90deg, #000, #000fe6, #000);
  background-repeat: no-repeat;
  background-size: 80%;
  animation: animate 3.75s linear infinite;
  -webkit-background-clip: text;
  -webkit-text-fill-color: rgba(45, 45, 45, .05);
  text-align: center;
}

@keyframes animate {
  0% {
    background-position: -500%;
  }
  100% {
    background-position: 500%;
  }
}
<body>
  <div>
    <p>Title</p>
    <p>Tag Line</p>
  </div>
</body>

1
投票

添加CSS

text-align:center

bodyp标签

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