Можно ли скрывать и отображать текст, используя только CSS (без кода JavaScript)? - программирование
Подтвердить что ты не робот

Можно ли скрывать и отображать текст, используя только CSS (без кода JavaScript)?

Можно ли показывать и скрывать текст, используя ссылку только с CSS - без использования JavaScript вообще?

Например: На этой странице

Обратите внимание на ссылку "Больше". Когда вы нажимаете на нее, она отображает текст. Этот пример - JavaScript, но я не уверен, что это можно сделать с помощью чистого CSS.

4b9b3361

Ответ 1

Theres элемент <details>, который еще не встроен в Edge:

<details>
  <summary>more <!-- a bad summary --></summary>
  <p>Some content</p>
</details>

Ответ 2

Да, это возможно с чистым CSS. Вы можете щелкнуть элемент, используя флажок :checked атрибут в сочетании с элементом <label> for атрибута.

Поскольку флажок может быть снят, вы можете использовать это для переключения видимости, просто добавляя visibility: hidden к элементу, вытекающих из :checked (когда флажок щелкнул снова, это псевдо-селектор будет недействительным, и больше не будет селектор CSS соответствовать цели).

Это можно расширить до <label> с использованием атрибута for, чтобы вы могли полностью скрыть этот флажок и применить свой собственный стиль к <label> напрямую.

Ниже использует примыкающий родственный комбинатор (+) для переключения класса toggle, когда <label> щелкнуть элемент:

input[type="checkbox"] {
  display: none; /* Hide the checkbox */
}

/* This is tied to the invisible checkbox */
label {
    background-color: #4CAF50;
    border: 2px solid black;
    border-radius: 20px;
    color: white;
    padding: 15px 32px;
    text-align: center;
    font-size: 16px;
    display: inline-block;
    margin-bottom: 20px;
    cursor: pointer;
    user-select: none;
}

/* The target element to toggle */
input[type="checkbox"]:checked + label + .toggle {
  visibility: hidden;
}
<input type="checkbox" id="checkbox" />
<label for="checkbox">Click me to toggle the content</label>
<div class="toggle">CONTENT</div>

Ответ 3

Да, вы можете легко сделать это, используя только CSS. См. Следующий код:

* {
  box-sizing: border-box;
}

body {
  background-color: #646464;
  color: #fff;
}

header {
  background-color: rgba(0, 0, 0, 0.5);
  font-size: 1.5em;
  text-align: center;
  padding: 1em;
}

.panel-wrapper {
  position: relative;
}

.btn {
  color: #fff;
  background: #000;
  border-radius: 1.5em;
  left: 30%;
  padding: 1em;
  text-decoration: none;
  width: 40%;
}

.show,
.hide {
  position: absolute;
  bottom: -1em;
  z-index: 100;
  text-align: center;
}

.hide {
  display: none;
}

.show:target {
  display: none;
}

.show:target~.hide {
  display: block;
}

.show:target~.panel {
  max-height: 2000px;
}

.show:target~.fade {
  margin-top: 0;
}

.panel {
  position: relative;
  margin: 2em auto;
  width: 70%;
  max-height: 100px;
  overflow: hidden;
  transition: max-height .5s ease;
}

.fade {
  background: linear-gradient(to bottom, rgba(100, 100, 100, 0) 0%, #646464 75%);
  height: 100px;
  margin-top: -100px;
  position: relative;
}
<!DOCTYPE html>
<html lang='en' class=''>

<head>
  <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css'>
</head>

<body>
  <header>CSS Only: Show More</header>
  <div class="panel-wrapper">
    <a href="#show" class="show btn" id="show">Show Full Article</a>
    <a href="#hide" class="hide btn" id="hide">Hide Full Article</a>
    <div class="panel">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In pharetra consectetur accumsan. Vestibulum vitae ipsum euismod, tempus ligula non, tempus lacus. Phasellus at pellentesque ex. Praesent at ipsum dui. Cras lectus neque, bibendum ac diam
        a, elementum tristique felis. Sed iaculis, diam at vehicula lacinia, odio urna tincidunt felis, sit amet scelerisque urna erat non leo. Pellentesque vel leo vitae tellus bibendum viverra.</p>
      <p>Donec id ultrices mi. Suspendisse potenti. Pellentesque cursus sagittis lacinia. Mauris elit sem, eleifend nec facilisis eget, fermentum sed odio. Nam aliquam massa nec leo tincidunt rhoncus. Integer tincidunt finibus tincidunt. Maecenas aliquam
        fermentum nisi, vitae mattis neque vehicula vitae.</p>
      <p>Nam orci purus, consequat sed lorem id, lacinia efficitur lorem. Vestibulum id quam ut elit congue varius. Donec justo augue, rhoncus non nisl ut, consectetur consequat velit. In hac habitasse platea dictumst. In hac habitasse platea dictumst. Aliquam
        auctor sapien lorem, at vestibulum justo congue vel. Duis volutpat, lorem quis tincidunt ornare, felis tortor posuere tellus, nec pretium neque velit vulputate libero.</p>
      <p>Morbi tortor tortor, auctor porttitor felis in, eleifend cursus ante. Nullam pellentesque lorem ipsum, in fringilla enim suscipit cursus. Pellentesque feugiat volutpat congue. Donec ac ante elit. Quisque ornare lacus dui, id commodo tortor lacinia
        nec. Curabitur dignissim magna sagittis neque aliquam porttitor. Aenean sit amet tincidunt risus.</p>
      <p>Cras feugiat, sapien luctus congue gravida, enim enim tristique nisl, vel porta lacus ante vitae dolor. Duis at nisl sed lectus imperdiet congue. Vestibulum pellentesque finibus ligula, sit amet elementum enim dignissim eget. Nullam bibendum justo
        eros, in placerat est ullamcorper nec. Donec blandit accumsan venenatis. Vivamus nec elit arcu. Morbi ultrices blandit sapien eget aliquam. Pellentesque placerat et libero a sodales. Donec eget erat ac velit maximus ullamcorper. Nulla laoreet
        dolor in purus sollicitudin varius. Duis eu erat ut magna lobortis rhoncus ac at lacus. Nullam in mi sed sem porttitor molestie. Aenean auctor dui in neque vulputate, in mattis purus tristique. Aliquam egestas venenatis ultricies. Nam elementum
        ante libero, nec dictum erat mollis dapibus. Phasellus pharetra euismod nibh, sit amet lobortis odio.</p>
      <p>Sed bibendum dapibus leo eu facilisis. Cras interdum malesuada diam id lobortis. Phasellus tristique odio eget placerat ornare. Phasellus nisl nulla, auctor convallis turpis tempus, molestie blandit urna. Nullam accumsan tellus massa, at tincidunt
        metus imperdiet sed. Donec sed imperdiet quam, id dignissim dolor. Curabitur mollis ultricies tempor. Morbi porttitor, turpis et dignissim aliquam, nunc lacus dignissim massa, a consequat nibh est vel turpis. Pellentesque blandit, ante vehicula
        sollicitudin imperdiet, tellus urna fringilla diam, id tempor neque augue eu nisl. Quisque eu sem posuere, vehicula risus ut, ullamcorper massa. Fusce vulputate bibendum erat, vel dapibus dui consectetur nec. Donec mauris mauris, egestas non malesuada
        non, finibus nec lacus. Duis at mauris tincidunt, accumsan augue non, vestibulum libero.</p>
      <p>Vestibulum fermentum vulputate lectus, at sollicitudin diam laoreet vitae. Aliquam erat volutpat. Nulla condimentum, arcu nec suscipit ultrices, urna tortor rutrum purus, sed mollis lacus ligula vitae justo. Duis vitae malesuada sem, eget finibus
        nibh. Etiam facilisis, urna ac blandit molestie, quam velit congue nibh, ac.</p>

    </div>
    <!-- end panel -->
    <div class="fade"></div>
  </div>
  <!-- end panel-wrapper -->

</body>

</html>

Ответ 4

Вы можете скрыть флажок, но разрешите его проверять/не проверять с помощью связанного с ним элемента <label>.

Исходя из того, установлен флажок или нет, вы можете скрыть/показать дополнительный текст и даже изменить текст метки с "Больше" на "Меньше".

Я включил некоторые дополнительные детали в CSS, чтобы каждый смысл определения мог быть немного более ясным.

1. С помощью одной кнопки "Больше"/"Меньше":

.more-text, #more-checkbox {          /* Hide the second paragraph and checkbox */
  display: none;
}

input:checked ~ .more-text {          /* Show the second paragraph when checked */
  display: block;
}

.more-label::after {                  /* Label underline, hand cursor, color */
  cursor: pointer;
  text-decoration: underline;
  color: #666;
}

input ~ .more-label::after {          /* Set label text to "More" by default */
  content: 'More';
}

input:checked ~ .more-label::after {  /* Set label text to "Less" when checked */
  content: 'Less';
}
<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ullamcorper, arcu ut facilisis interdum, lacus felis fringilla nulla, vel scelerisque massa quam vel leo.
</p>

<input type="checkbox" id="more-checkbox" />
<label class="more-label" for="more-checkbox"></label>

<p class="more-text">
  Sed a ullamcorper ex. In elementum purus ullamcorper justo gravida aliquet. Aliquam erat volutpat. Maecenas in ante quam.
</p>

Ответ 5

С технической точки зрения, можно переключать видимость текста на основе того, когда вы нажимаете на кнопку или ссылку, как показано ниже:

.hidden-text {
  display: none;
}

.toggle-text:focus + .hidden-text {
  display: block;
}
<p>
  This is an example with no hidden content until you... <a href="#" class="toggle-text">read more</a>!
  <span class="hidden-text">Now I'm visible!!!</span>
</p>

Ответ 6

Да, вы можете это сделать, используя только HTML и CSS.

body { padding: 20px; }

div { margin-top: 10px; border: 1px solid black; width: 200px; height: 100px;
    padding: 5px;
}
input:checked + label + div { display: none; }
input + label:after { content: " To Hide"; }
input:checked + label:after { content: " To Show"; }

label {
    background-color: yellow;
    box-shadow: inset 0 2px 3px rgba(255,255,255,0.2), inset 0 -2px 3px rgba(0,0,0,0.2);
    border-radius: 4px;
    font-size: 16px;
    display: inline-block;
    padding: 2px 5px;
    cursor: pointer;
}
<input type='checkbox' style='display: none' id=cb>
<label for=cb>Click Here</label>
<div>
    Hello. This is some stuff.
</div>

Ответ 7

теперь вы можете скрыть/показать текст, используя только CSS! Если вы используете ввод текста и хотите показать/скрыть текст в зависимости от состояния окна ввода, вы можете использовать новый псевдо-класс CSS :placeholder-shown для <input> или <textarea>. Вот пример/демонстрация вышеупомянутого псевдокласса !:

/* Some base style  */
.app {
  margin: 10px auto;
  padding: 10px;
}

code {
  background-color: lightgray;
  padding: 4px;
}

input {
  padding: 5px 10px;
}

input:focus {
  outline: none;
}

/* When there is something in input box give 
  it a solid blue border */

input:not(:placeholder-shown) {
  border: solid 2px #42A5F5
}

/* Hide the p initially */
p {
  background-color: #F0F4C3;
  padding: 5px;
  opacity: 0;
  transition: all 300ms ease-in-out;
}


/* Show the p when the placeholder is not shown. 
  i.e. Something is in the input box and placeholder is gone */
input:not(:placeholder-shown)+p {
  opacity: 1
}
<div class="app">
  <h1>Hide/Show Text using input <code>:placehoder-shown</code> psuedo class!</h1>
  <label for="name">Enter your name</label>
  <input type="text" id="name" placeholder="Your Name">
  <p class="msg">Well done!</p>
</div>

Ответ 8

Возможно, кто-то найдет это решение более интуитивным и более простым в реализации. Механика этого заключается в том, что ссылка нацеливается на себя, и в этом случае легко выбрать все, что будет дальше в DOM.

.toggle-hide,
.toggle-content {
  display: none;
}
.toggle-show:target + .toggle-hide,
.toggle-show:target + .toggle-hide + .toggle-content {
  display: block;
}
.toggle-show:target {
  display: none;
}
<a id="target" class="toggle-show" href="#target">Show</a>
<a class="toggle-hide" href="#" >Hide</a>
<p class="toggle-content">Lorem ipsum</p>

Ответ 9

Использовать "display: none;" attribute. "display: none;" attribute.