边框中带有彩色背景的 CSS 标签

问题描述 投票:0回答:1

我正在努力得到这个:

enter image description here

问题是我没有线性背景。

我有这样的背景: enter image description here

有没有办法无需为标签设置背景颜色即可达到该结果?

我知道这个方法:

input {  
  border: none;
  font-size: 16px;
  outline: 0;
  padding: 16px 0 10px;    
  width: 100%;
}

label {
  font-size: 12px;
  position: absolute;
  top: -6px;
  left: 10px;
  background: white;
}

但是就像我说的,将背景设置为某种颜色并不是正确的方法,因为背景颜色不是线性的。

我无法使用

<fieldset>

html css
1个回答
0
投票

要在非线性背景上实现浮动标签效果,而不需要为标签设置纯色背景色,您可以利用伪元素、

::before
::after
的组合以及CSS技巧来模仿标签背后的背景。标签。

这是一种解决方法:

解决方案:

您可以使用

::before
::after
伪元素“掩盖”标签后面的部分,使其融入背景,而不影响标签文本本身,而不是直接在标签上设置背景颜色。这是一个可能的解决方案:

<div class="form-group">
  <input type="text" id="input-field" required>
  <label for="input-field">Your Label</label>
</div>
.form-group {
  position: relative;
  margin-bottom: 20px;
}

input {
  border: none;
  font-size: 16px;
  outline: 0;
  padding: 16px 0 10px;
  width: 100%;
  background: transparent;
  position: relative;
  z-index: 1; /* Keeps input field above the label background */
}

label {
  font-size: 12px;
  position: absolute;
  top: -6px;
  left: 10px;
  padding: 0 5px;
  z-index: 2; /* Ensures the label text stays on top */
}

/* Create background with pseudo-elements to mimic the background "cutout" */
label::before {
  content: '';
  position: absolute;
  top: 0;
  left: -5px;
  right: -5px;
  bottom: 0;
  background: inherit; /* Takes the parent’s background */
  z-index: -1; /* Send the pseudo-element behind the label text */
}

说明:

  1. 伪元素

    ::before
    :我们在标签上使用
    ::before
    伪元素来模仿标签文本背后的背景。该伪元素将使用
    .form-group
    获取父元素 (
    background: inherit
    ) 的背景。

  2. 标签上没有纯色背景

    label
    元素没有纯色背景色,因此不会破坏您的非线性背景。

  3. Z-index:输入字段保留在带有

    z-index: 1
    的所有内容之上,而标签堆叠在伪元素 (
    z-index: 2
    ) 上方,伪元素放置在标签文本 (
    z-index: -1) 下方
    )。

这种方法使标签保持浮动,不需要标签背景为纯色,并确保输入后面的非线性背景保持不变。

© www.soinside.com 2019 - 2024. All rights reserved.