使用切换和单个元素的文本创建按钮

问题描述 投票:2回答:3

我正在尝试用单个html元素创建一个按钮。按钮需要有一个切换滑块,文本需要垂直和水平对齐。所以我认为我可以利用:before元素来帮助我实现这一目标。这是我尝试过的:

div {
  width: 140px;
  height: 40px;
  background-color: #B3B3B3;
  color: #FFF;
  float: left;
  clear: both;
  border-radius: 5px;
  font-size: 12px;
}

div:before {
  content: '';
  display: block;
  width: 20px;
  height: 36px;
  background-color: #4D4D4D;
  position: relative;
  left: 2px;
  top: 2px;
  float: left;
  border-radius: 5px;
}
<div>Text Value</div>

我有上述代码的2个问题:

  1. 我无法将文本放在我想要的位置,我尝试使用text-align和position来移动它。
  2. 我使用浮动,这意味着它会影响其周围的其他元素的行为,我真的不希望这样。

单个元素是我想要的吗?

这是JS小提琴:https://jsfiddle.net/m3q5Lcjy/

编辑:居中文本不应以整个元素为中心,而应以浅灰色区域为中心。

html css html5 css3
3个回答
4
投票

这就是我要这样做的方式:

Array.from(document.querySelectorAll('.toggler')).forEach((item) => {
  item.addEventListener('click', e => {
    item.classList.toggle('active');
  })
});
.toggler {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  box-sizing: border-box;
  padding-left: 24px;
  width: 140px;
  min-height: 40px;
  background-color: #B3B3B3;
  color: #FFF;
  border-radius: 5px;
  font-size: 12px;
  text-align: center;
  cursor: pointer;
  transition: padding .25s ease;
}

.toggler.active {
  padding: 0 24px 0 0;
}

.toggler:before {
  content: '';
  display: block;
  width: 20px;
  background-color: #4D4D4D;
  position: absolute;
  bottom: 2px;
  left: 2px;
  top: 2px;
  border-radius: 5px;
  /* transition to make it look smoother */
  transition: left .4s ease;
  z-index: 1;
}

.toggler.active:before {
  left: calc(100% - 22px);
}
<div class="toggler">Text Value</div>
<hr />
<div class="toggler active">Text Value realllllyy long</div>
<hr />
<div class="toggler">Text Value really far too long for this tiny, tiny, ohhh so tiny button. I recommend using shorter text though, but it won't break not even if you have like 10 or more lines.</div>

如果有任何关于此实现的信息不清楚,请随时提出。


3
投票

使用flexbox可以垂直和水平居中显示文本。然后在伪元素上使用绝对定位。确保父元素已应用相对定位,因此绝对定位伪保留​​在父元素内。

div {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  box-sizing: border-box;
  padding-left: 24px; /* 20px for :before width, 4px for :before offset */
  
  width: 140px;
  height: 40px;
  background-color: #B3B3B3;
  color: #FFF;
  border-radius: 5px;
  font-size: 12px;
}

div:before {
  content: '';
  display: block;
  width: 20px;
  height: 36px;
  background-color: #4D4D4D;
  position: absolute;
  left: 2px;
  top: 2px;
  border-radius: 5px;
}
<div>Text Value</div>

0
投票

您可以将文本放在段落中。

<div class="thediv">
    <p class="theText">
    enter text here
    </p>
</div>



.thediv{
Your own style.
}

.theText{
position: absolute;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
}

我不明白为什么你会想要它在一个元素中。如果你想要那个,你应该给div一个填充。

div{
  background-color: #B3B3B3;
  color: #FFF;
  float: left;
  border-radius: 5px;
  font-size: 12px;
  padding: 20px 70px;
}
© www.soinside.com 2019 - 2024. All rights reserved.