css - 需要使用 less(css) 在垂直和水平方向上居中对齐 div 内的跨度

标签 css

我正在使用 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);
}

最佳答案

您可以使用 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。

关于css - 需要使用 less(css) 在垂直和水平方向上居中对齐 div 内的跨度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20327083/

相关文章:

javascript - 点击图像

css - Fieldset 奇怪的图例下划线问题

jquery - 使用 jquery 的背景定位在 IE7 中不起作用

html - 最小化窗口时右边距丢失

CSS keyframe-mobile 在动画之前从 100% 开始

html - 这个 "Quine"代码如何详细工作?

html - 如何编写网站代码以便缓存来自远程站点的 jscript,而不是不断重新加载

css - 导航选项卡事件时刻图像不会改变

javascript - 如何在 CSS 中延长悬停持续时间

jquery - 无法让 jQuery slider 工作