需要使用less(css)在div内垂直和水平居中对齐一个跨度



我使用LESS(CSS)试图在div(按钮)内对齐span(按钮文本)。跨度在水平方向居中对齐,但在垂直方向顶部对齐。我还希望span对象能够自动将自己调整为文本大小。

这是LESS代码:

.button(@color:@crimson-red) {
  border-radius: @small-border-radius;
  border-style: none;
  background-color: @color;
  text-align: center;
  display: inline-block;
}
.button-font {
  vertical-align: middle;
  overflow: auto;
  font-family: "Helvetica Neue", sans-serif;
  color: @off-white;
  font-weight: bold;
  font-size: 10pt;
  position: relative;
}
.blue-button {
  .button(@blue);
}

您可以通过使用flexbox布局来实现这一点。

因此,通过将以下属性和值添加到.button选择器,您可以将span居中。

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

这是完整的less文件供参考。

@off-white: #fefefe;
@blue: #4286f4;
@small-border-radius: 5px;
.button(@color:@crimson-red) {
  border-radius: @small-border-radius;
  border-style: none;
  background-color: @color;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.button-font {
  font-family: "Helvetica Neue", sans-serif;
  color: @off-white;
  font-weight: bold;
  font-size: 10pt;
  position: relative;
}
.blue-button {
  .button(@blue);
  width: 300px;
  height: 100px;
}

这将是html:

<button class="blue-button">
    <span class="button-font">Hello, lots of text here</span>
</button>

这里有一个链接,指向一个带有已编译css的JSFiddle。

最新更新