首页 > 解决方案 > 如何在 div 中将 span 元素居中?

问题描述

我正在构建这个应用程序,我希望这个标题居中。我希望这样当我将鼠标悬停在文本上时,它会增加字体并改变颜色。起初我选择使用<div>,但由于它占据了一整行,当我将鼠标悬停在文本上而不是在行的任何点上时,文本会突出显示。所以然后我决定使用<span>并遇到了所述的问题。

所以我有这个:

.welcome {
  border-width: 4px;
  border-style: solid;
  border-color: red;
  border-radius: 50px;
  position: fixed;
  top: 50%;
  left: 50%;
  margin-top: -310px;
  margin-left: -600px;
  height: 600px;
  width: 1200px;
}

.button {
  color: green;
}

.button:hover {
  transform: scale(1.2);
  color: blue;
}

.title {
  font-size: 120px;
  /*
    float: center;
    align-content: center;
    text-align: center;
    */
  position: relative;
  top: 35%;
}
<div class="welcome">
  <span class="button title"> Mancala </span>
</div>

被评论的部分是我最后一次尝试将“Mancala”居中,即跨度元素。

我正在使用两个类(按钮和标题),因为我将有多个元素,我希望它们在悬停时突出显示。在此先感谢您的帮助!

标签: htmlcss

解决方案


调试代码后,这是一个解决方案。用这个替换你的 CSS 代码。我所做的是我使用了 flex 属性。由于 .welcome 的宽度为 1200px 并且使用命令display: flex;和.welcome justify-content: center;div 中的所有内容都将水平居中。

    .welcome {
      border-width: 4px;
      border-style: solid;
      border-color: red;
      border-radius: 50px;
      position: fixed;
      top: 50%;
      left: 50%;
      margin-top: -310px;
      margin-left: -600px;
      height: 600px;
      width: 1200px;
      background: orange;
      display: flex;
      justify-content: center;
    }
    
    .button {
      color: green;
    }
    
    .button:hover {
      transform: scale(1.2);
      color: blue;
    }
    
    .title {
      font-size: 120px;
      /*
        float: center;
        align-content: center;
        text-align: center;
        */
      position: relative;
      text-align: center;
      top: 35%;
    }
<div class="welcome">
  <span class="button title"> Mancala </span>
</div>


推荐阅读