如何对齐 css 内容字符串

how to align css content string

大家好,我从复选框创建了一个切换按钮。我有一个来自 awesome font 的图标作为 css 内容。我已经尝试了几乎所有的方法,但我不会在圆圈中间对齐 css 内容字符串。

这里是css内容部分:

.onoffswitch-label:before {
    content: "\f000";
    font-family: FontAwesome;
    display: block;
    width: 30px;
    height: 30px;
    margin: 4px 4px 0 0;
    background-color: #59B200;
    color: #fff;
    position: absolute;
    top: 0;
    bottom: 0;
    right: 52px;
    border: 2px solid #59B200;
    border-radius: 38px;
    transition: all 0.3s ease-in 0s;
}

这是完整的例子

http://jsfiddle.net/vzjyyob4/

感谢您的帮助

您可以使用 text-align: center 使图标水平居中,然后将 line-height 设置为所需的值以使其垂直对齐。

这是标签的 CSS:

text-align: center;
line-height: 32px;

这是一个更新的 JSFiddle:http://jsfiddle.net/vzjyyob4/1/


这里是一个在线 现场演示:

.onoffswitch {
  position: relative;
  width: 94px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}
.onoffswitch-checkbox {
  display: none;
}
.onoffswitch-label {
  display: block;
  overflow: hidden;
  cursor: pointer;
  height: 38px;
  padding: 0;
  line-height: 38px;
  border: 2px solid #59B200;
  border-radius: 38px;
  background-color: #FFFFFF;
  transition: all 0.3s ease-in;
}
.onoffswitch-label:before {
  content: "\f000";
  font-family: FontAwesome;
  display: block;
  width: 30px;
  height: 30px;
  margin: 4px 4px 0 0;
  background-color: #59B200;
  color: #fff;
  position: absolute;
  top: 0;
  bottom: 0;
  right: 52px;
  border: 2px solid #59B200;
  border-radius: 38px;
  transition: all 0.3s ease-in 0s;
  text-align: center;
  line-height: 32px;
}
.onoffswitch-checkbox:checked + .onoffswitch-label {
  background-color: #59B200;
}
.onoffswitch-checkbox:checked + .onoffswitch-label {
  border-color: #59B200;
}
.onoffswitch-checkbox:checked + .onoffswitch-label:before {
  border-color: #fff;
  background-color: #fff;
  color: #59B200;
}
.onoffswitch-checkbox:checked + .onoffswitch-label:before {
  right: 0px;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" />
<div class="onoffswitch">
  <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>
  <label class="onoffswitch-label" for="myonoffswitch"></label>
</div>

只需添加这条 CSS 规则来对齐内容:

.onoffswitch-label:before {
    text-align: center;
}

试一试here

使用 line-height 属性:

.onoffswitch-label:before {
    text-align: center;
    line-height: 32px;
}

或者 flexbox:

.onoffswitch-label:before {
    display: flex;
    align-items: center;
    justify-content: center;
}