【问题标题】:Need to center align a span inside a div both vertically and horizontally using less(css)需要使用 less(css) 将 div 内的 span 垂直和水平居中对齐
【发布时间】:2013-12-02 11:22:44
【问题描述】:

我正在使用 LESS (CSS) 尝试对齐 div(按钮)内的跨度(按钮文本)。跨度水平居中对齐,但垂直顶部对齐。我还希望 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);
}

【问题讨论】:

  • 你能分享 html 或创建你迄今为止创建的小提琴吗?
  • 没有硬编码的 html。它全部由 JQuery 动态生成。 .blue-button 类应用于 div,而 button-font 应用于 span。
  • 动态代码生成的HTML是什么,可以分享一下吗?
  • 这并不是一个真正的 LESS 问题,而是一个 CSS 问题。但是therestack overflow 上有很多answers

标签: css


【解决方案1】:

您可以使用flexbox layout 来实现此目的。

因此,通过将以下属性和值添加到 .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>

这是一个链接到 JSFiddle 与编译的 css。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-15
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多