Как мне сделать эту фоновую кнопку?

Мне нужно сделать фон для кнопок переключения темы, но я застрял на этой части.

Как должно быть ->

Как я это делал ->

это мой код в нижней части темы переключения

<div class = "themeContainer">
      <p>calc</p>
      <div>
        <span class = "themeText">THEME</span>
        <span class = "btnContainer">
          <button id = "switchTheme1">1</button>
          <button id = "switchTheme2">2</button>
          <button id = "switchTheme3">3</button>
        </span>
      </div>
    </div>

Сначала я создал контейнер <span>, чтобы другие элементы не разрывали строку, но поскольку диапазон естественным образом отображается в строке, я не могу изменить его высоту.

После этого я попытался изменить btnContainer для отображения: inline-block; но это не сработало

Теперь я немного растерян, был бы признателен, если бы кто-нибудь помог мне в этом вопросе.

.themeContainer {
   color: hsl(0, 0%, 100%);
   width: 535px; 
   height: 40px;
   display: flex;
   justify-content: space-between;
   align-items: center;
}

.themeContainer p {
    font-size: 30px;
    margin-left: 10px;
}

.themeContainer .btnContainer {
    background-color:hsl(224, 36%, 15%);
    border-radius: 50%;
}

.themeContainer .themeText {
    font-size: 12px;
    margin-right: 10px;
}

.themeContainer button {
    color: hsl(0, 0%, 100%);
    background-color:hsl(224, 36%, 15%);
    font-size: 12px;
    max-width: 50px;
    max-height: 50px;
    width: 20px;
    height: 20px;
    margin: -1px;
    border-radius: 50%;
    border-style: none;
    cursor: pointer;
}

Примерно так Codepen ?

Zak 19.04.2024 20:21

Посмотрите на тип ввода = «диапазон» и шаги.

A Haworth 19.04.2024 21:15
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Введение в CSS
Введение в CSS
CSS является неотъемлемой частью трех основных составляющих front-end веб-разработки.
Как выровнять Div по центру?
Как выровнять Div по центру?
Чтобы выровнять элемент <div>по горизонтали и вертикали с помощью CSS, можно использовать комбинацию свойств и значений CSS. Вот несколько методов,...
Навигация по приложениям React: Исчерпывающее руководство по React Router
Навигация по приложениям React: Исчерпывающее руководство по React Router
React Router стала незаменимой библиотекой для создания одностраничных приложений с навигацией в React. В этой статье блога мы подробно рассмотрим...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
Toor - Ангулярный шаблон для бронирования путешествий
Toor - Ангулярный шаблон для бронирования путешествий
Toor - Travel Booking Angular Template один из лучших Travel & Tour booking template in the world. 30+ валидированных HTML5 страниц, которые помогут...
1
2
59
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Я бы предпочел, чтобы вы использовали radio-input, чтобы добиться этого с помощью CSS-selectors.

.theme-switch {
  display: inline-block;
  position: relative;
  background-color: #eee;
  padding: 10px 20px;
  border-radius: 20px;
}

.theme-switch input[type = "radio"] {
  display: none;
}

.theme-switch label {
  cursor: pointer;
  padding: 10px 20px;
  background-color: #eee;
  border-radius: 20px;
  color: #333;
}

.slider {
  position: absolute;
  top: 0;
  left: 0;
  width: calc(100% / 3);
  height: 100%;
  background-color: #333;
  border-radius: 20px;
  transition: left 0.3s ease;
}

.theme-switch input[type = "radio"]:nth-of-type(1):checked~.slider {
  left: 0%;
}

.theme-switch input[type = "radio"]:nth-of-type(2):checked~.slider {
  left: calc(100% / 3);
}

.theme-switch input[type = "radio"]:nth-of-type(3):checked~.slider {
  left: calc(100% / 3 * 2);
}
<div class = "theme-switch">
  <input type = "radio" id = "lightTheme" name = "theme" value = "light">
  <label for = "lightTheme">Light</label>

  <input type = "radio" id = "midDarkTheme" name = "theme" value = "mid-dark">
  <label for = "midDarkTheme">Mid-Dark</label>

  <input type = "radio" id = "darkTheme" name = "theme" value = "dark">
  <label for = "darkTheme">Dark</label>

  <div class = "slider"></div>
</div>
Ответ принят как подходящий

Вы можете внести некоторые окончательные корректировки.. Но я отредактировал ЭТОТ КОД в соответствии с вашими потребностями.

.tw-toggle {
  background: #252D44;
  display: inline-block;
  padding: 2px 3px;
  border-radius: 20px;
  position: relative;
  border: 2px solid #95A5A6;
}

.tw-toggle label {
  text-align: center;
  font-family: sans-serif;
  display: inline-block;
  color: #95A5A6;
  position: relative;
  z-index: 2;
  margin: 0;
  text-align: center;
  padding: 2px 3px;
  font-size: 20px;
  margin: 5px
  /* cursor: pointer; */
}

.tw-toggle input {
  /* display: none; */
  position: absolute;
  z-index: 3;
  opacity: 0;
  cursor: pointer;
  height: 30px;
  width: 30px;
}

.tw-toggle span {
  height: 30px;
  width: 30px;
  line-height: 21px;
  border-radius: 50%;
  background: #fff;
  display: block;
  position: absolute;
  left: 15px;
  top: 2px;
  transition: all 0.3s ease-in-out;
}

.tw-toggle input[value = "false"]:checked~span {
  background: rgb(249, 107, 89);
  left: 2px;
  top: 5px;
  color: #fff;
}

.tw-toggle input[value = "true"]:checked~span {
  background: rgb(249, 107, 89);
  left: 64px;
  top: 5px;
  color: #fff;
}

.tw-toggle input[value = "-1"]:checked~span {
  background: rgb(249, 107, 89);
  left: 33px;
  top: 5px;
  color: #fff;
}

.tw-toggle input[value = "false"]:checked+label,
.tw-toggle input[value = "true"]:checked+label {
  color: #fff;
}

.tw-toggle input[value = "-1"]:checked+label {
  color: #fff;
}
<div class = "tw-toggle">
  <input type = "radio" name = "toggle" value = "false">
  <label class = "toggle toggle-yes">1</label>
  <input checked type = "radio" name = "toggle" value = "-1">
  <label class = "toggle toggle-yes">2</label>
  <input type = "radio" name = "toggle" value = "true">
  <label class = "toggle toggle-yes">3</label>
  <span></span>
</div>

Другая итерация, более близкая к оригиналу, может быть:

.tw-toggle {
  background: #252D44;
  display: inline-block;
  padding: 2px 3px;
  border-radius: 20px;
  position: relative;
  border: 2px solid #95A5A6;
}

.tw-toggle label {
  text-align: center;
  font-family: sans-serif;
  display: inline-block;
  color: #95A5A6;
  position: relative;
  z-index: 2;
  margin: 0;
  text-align: center;
  padding: 2px 3px;
  font-size: 20px;
  margin: 5px
  /* cursor: pointer; */
}

.tw-toggle input {
  /* display: none; */
  position: absolute;
  z-index: 3;
  opacity: 0;
  cursor: pointer;
  height: 30px;
  width: 30px;
}

.tw-toggle span {
  height: 30px;
  width: 30px;
  line-height: 21px;
  border-radius: 50%;
  background: #fff;
  display: block;
  position: absolute;
  left: 15px;
  top: 2px;
  transition: all 0.3s ease-in-out;
}

.tw-toggle input[value = "false"]:checked~span {
  background: rgb(249, 107, 89);
  left: 3px;
  top: 5px;
  color: #fff;
}

.tw-toggle input[value = "true"]:checked~span {
  background: rgb(249, 107, 89);
  left: 64px;
  top: 5px;
  color: #fff;
}

.tw-toggle input[value = "-1"]:checked~span {
  background: rgb(249, 107, 89);
  left: 33px;
  top: 5px;
  color: #fff;
}

.tw-toggle input[value = "false"]:checked+label,
.tw-toggle input[value = "true"]:checked+label {
  color: #fff;
}

.tw-toggle input[value = "-1"]:checked+label {
  color: #fff;
}
<div style = "padding:0 15px; width:70px; display: flex;
    justify-content: space-between; font-weight:bold;">
  <div>
    1
  </div>
  <div>
    2
  </div>
  <div>
    3
  </div>
</div>
<div class = "tw-toggle">
  <input type = "radio" name = "toggle" value = "false">
  <label class = "toggle toggle-yes">&nbsp&nbsp</label>
  <input checked type = "radio" name = "toggle" value = "-1">
  <label class = "toggle toggle-yes">&nbsp&nbsp</label>
  <input type = "radio" name = "toggle" value = "true">
  <label class = "toggle toggle-yes">&nbsp&nbsp</label>
  <span></span>
</div>

Другие вопросы по теме