Как поставить разделитель строк для каждой строки текста в абзаце, используя css? - PullRequest
4 голосов
/ 04 августа 2020

Я пытаюсь отобразить абзац с разделителями строк между строками текста, используя css. После некоторого исследования css я нашел только текстовое оформление и тег <hr>. В моем случае ничего из этого не сработает.

<div  style="text-decoration:underline">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer dolor est, condimentum id fringilla eget, vulputate nec odio. Fusce a metus feugiat, euismod urna eu, pretium lacus. Aenean semper sollicitudin felis eget viverra. Mauris feugiat sem non arcu malesuada rhoncus. Sed placerat in dolor eu dignissim. Proin aliquam odio non arcu hendrerit, ut ultrices ex dignissim. Suspendisse convallis ultricies nulla id vehicula. Sed et sem bibendum, 
</div>

У меня нет информации о количестве строк во время выполнения, поэтому я не могу использовать тег <hr>.

Желаемый результат:

first line of text in a paragraph 
---------------------------------
second line of text in the same p
---------------------------------
third line of text same paragraph
---------------------------------
and so on. End of paragraph. 

Обратите внимание, что под последней строкой текста нет строки.

Ответы [ 5 ]

3 голосов
/ 04 августа 2020

Фон может это сделать. Вам просто нужно настроить line-height и padding-bottom в зависимости от шрифта, который вы используете

.box span {
  background: linear-gradient(black, black) bottom/100% 1px no-repeat;
  padding-bottom: 0.2em; /* you may have to adjust this */
}

.box {
  overflow: hidden; /* hide the last line */
  line-height: 1.3em; /* you may have to adjust this */
  /* text-align:justify uncomment this to justify the text*/
}
<div class="box">
  <span>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer dolor est, condimentum id fringilla eget, vulputate nec odio. Fusce a metus feugiat, euismod urna eu, pretium lacus. Aenean semper sollicitudin felis eget viverra. Mauris feugiat sem non arcu malesuada rhoncus. Sed placerat in dolor eu dignissim. Proin aliquam odio non arcu hendrerit, ut ultrices ex dignissim. Suspendisse convallis ultricies nulla id vehicula. Sed et sem bibendum, 
</span>
</div>

<div class="box" style="font-size:20px;">
  <span>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer dolor est, condimentum id fringilla eget, vulputate nec odio. Fusce a metus feugiat, euismod urna eu, pretium lacus. Aenean semper sollicitudin felis eget viverra. Mauris feugiat sem non arcu malesuada rhoncus. Sed placerat in dolor eu dignissim. Proin aliquam odio non arcu hendrerit, ut ultrices ex dignissim. Suspendisse convallis ultricies nulla id vehicula. Sed et sem bibendum, 
</span>
</div>

Граница также может делать то же самое:

.box span {
  border-bottom:1px solid black;
  padding-bottom: 0.1em; /* you may have to adjust this */
}

.box {
  overflow: hidden; /* hide the last line */
  line-height: 1.3em; /* you may have to adjust this */
  /* text-align:justify uncomment this to justify the text*/
}
<div class="box">
  <span>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer dolor est, condimentum id fringilla eget, vulputate nec odio. Fusce a metus feugiat, euismod urna eu, pretium lacus. Aenean semper sollicitudin felis eget viverra. Mauris feugiat sem non arcu malesuada rhoncus. Sed placerat in dolor eu dignissim. Proin aliquam odio non arcu hendrerit, ut ultrices ex dignissim. Suspendisse convallis ultricies nulla id vehicula. Sed et sem bibendum, 
</span>
</div>

<div class="box" style="font-size:20px;">
  <span>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer dolor est, condimentum id fringilla eget, vulputate nec odio. Fusce a metus feugiat, euismod urna eu, pretium lacus. Aenean semper sollicitudin felis eget viverra. Mauris feugiat sem non arcu malesuada rhoncus. Sed placerat in dolor eu dignissim. Proin aliquam odio non arcu hendrerit, ut ultrices ex dignissim. Suspendisse convallis ultricies nulla id vehicula. Sed et sem bibendum, 
</span>
</div>

Другая идея, если вы хотите охватить всю строку:

.box {
  overflow: hidden;
  font-size:15px;
  line-height: 1.4em; 
  background:
    repeating-linear-gradient(to bottom,transparent 0 calc(1.4em - 1px), black 0 1.4em)
     0 0/100% calc(100% - 1em);
  /* text-align:justify uncomment this to justify the text*/
}
<div class="box">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer dolor est, condimentum id fringilla eget, vulputate nec odio. Fusce a metus feugiat, euismod urna eu, pretium lacus. Aenean semper sollicitudin felis eget viverra. Mauris feugiat sem non arcu malesuada rhoncus. Sed placerat in dolor eu dignissim. Proin aliquam odio non arcu hendrerit, ut ultrices ex dignissim. Suspendisse convallis ultricies nulla id vehicula. Sed et sem bibendum, 
</div>

<div class="box" style="font-size:20px;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer dolor est, condimentum id fringilla eget, vulputate nec odio. Fusce a metus feugiat, euismod urna eu, pretium lacus. Aenean semper sollicitudin felis eget viverra. Mauris feugiat sem non arcu malesuada rhoncus. Sed placerat in dolor eu dignissim. Proin aliquam odio non arcu hendrerit, ut ultrices ex dignissim. Suspendisse convallis ultricies nulla id vehicula. Sed et sem bibendum, 
</div>
0 голосов
/ 04 августа 2020

div {

  width: 300px;

}

span {
     position: relative;
  padding-bottom: 10px;
  border-bottom: 1px dashed pink;
  line-height: 48px;
  
   
}
<div>
  <span id="span">How to increase the gap between text and underlining in CSS How to increase the gap between text and underlining in CSS How to increase the gap between text and underlining in CSS</span>
</div>
0 голосов
/ 04 августа 2020

Это связано с небольшим трюком, в этом случае у нас есть предопределенная высота строки

В моем примере я решил 30 пикселей в качестве фиксированной высоты строки для абзаца , затем Я создаю простое изображение размером 1px x30px PNG, например:

image

  .container{
        background-image: url('https://img.techpowerup.org/200804/dottedline.png');
        background-repeat: repeat;
        background-size:1px 30px;
        background-position: bottom;
        overflow:hidden;
         box-sizing: border-box;

         box-shadow: inset 0px 0px 0px 1px #fff;
    }

    .paragraph{
        line-height: 30px;
        overflow: hidden;
    }
 <div class="container">
        <div class="paragraph">
            The quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dog
        </div>
    </div>

смотри, что я использую box-shadow: inset css в контейнере, чтобы скрыть последнюю границу абзаца.

если вы решите изменить высоту строки, просто измените высоту изображения и высоту строки.

о, это тоже отзывчиво, мои парни ..

0 голосов
/ 04 августа 2020

Если контейнер имеет фиксированную ширину, вы можете обернуть текст в div и установить для свойства "text-decoration" значение "underline", заключить последнюю строку в тег span и установить для его свойства "text-decoration" значение "none".

ПРИМЕЧАНИЕ: Только последняя строка должна быть заключена в тег span, а свойство "display" тега span должно быть установлено на "inline-block".

.paragraph {
  text-decoration: underline;
}

.last {
  display: inline-block;
  text-decoration: none;
}
<div class="paragraph">
  Lorem Ipsum Lorem Ipsum The quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown
  fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick
  brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown
  <span class="last">fox jumps over the lazy dog</span>
</div>
0 голосов
/ 04 августа 2020

Вы можете сделать это с помощью Javascript. Что это означает, он помещает оболочку вокруг каждой строки, и вы можете стилизовать ее по своему вкусу

Я сделал это применимо ко всем абзацам с классом paragraph. Контейнер - это то, на что это похоже, контейнер для демонстрации. Но я думаю, вы догадались об этой части.

function wrapLines(element) {
    const container = element
  const spans = container.children
  var top = 0
  var tmp = ''
  const opentag = '<span class="paragraph__inner-text">'
  const closingtag = '</span>'

  container.innerHTML = container.textContent.replace(/\S+/g, '<n>$&</n>')
  for (let i = 0; i < spans.length; i++) {
    const rect = spans[i].getBoundingClientRect().top

    if (top < rect) {
      tmp += closingtag + opentag
    }

    top = rect
    tmp += spans[i].textContent + ' '
  }

  container.innerHTML = tmp += closingtag
  container.classList.add('paragraph--rendered')
}

const paragraph = document.querySelectorAll('.paragraph')
paragraph.forEach((p) => {
    wrapLines(p)
})
.container {
  max-width: 20rem;
}

.paragraph__inner-text {
  display: inline-block;
  border-bottom: 1px solid aqua;
}
<div class="container">
  <p class="paragraph">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Asperiores, voluptate eaque temporibus et quos aut praesentium excepturi sapiente laboriosam itaque, dolorem minima expedita. Ut repellat voluptatum odio sint, enim eos eveniet facere asperiores qui quod mollitia nesciunt iure voluptate autem veniam culpa atque, fugiat dolorum minima, voluptates tempora magni architecto.
  </p>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...