Заголовок на 2 строках в CSS

#css

Вопрос:

По эстетическим соображениям я хотел бы, чтобы заголовок занимал максимум доступного места, но в 2 строки. Я хотел бы использовать только CSS. Вот мой код:

 .title {
  white-space: nowrap;
  font-size: 4vw;
} 
 <h1 class="title">
  Lorem ipsum dolor sit amet,<br> consectetur adipiscing elit
</h1> 

Это немного работает, но я думаю, что есть и получше.

Ответ №1:

Вы могли бы использовать max-width в паре с white-space

 .title {
  white-space: nowrap;
  font-size: 4vw;
  max-width: 30ch;
  white-space: pre-wrap;
} 
 <h1 class="title">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit
</h1> 

Ответ №2:

Попробуйте этот пример…

 .parent {
    width: 300px;
}

.ellipsis {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.block-ellipsis {
  display: block;
  display: -webkit-box;
  max-width: 100%;
  height: 28px;
  margin: 0 auto;
  font-size: 14px;
  line-height: 1;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
} 
 <div class="parent">
    <h2>Single Line Ellipsis</h2>
    <div class="ellipsis">
        This is an example of an ellipsis. once we reach 300px of length then the text will be cut off.
    </div>
    <h2>Multiple Line Ellipsis</h2>
    <div class="block-ellipsis">
        This is an example of a multi-line ellipsis. We just set the number of lines we want to display before the ellipsis takes into effect and make some changes to the CSS and the ellipsis should take into effect once we reach the number of lines we want.
    </div>
</div> 

Комментарии:

1. Ваша альтернатива может быть очень интересной, например, домашняя страница блога, на которой перечислены все статьи. Это не решает мою текущую проблему, потому что мне нужно прочитать весь заголовок; но я сохраняю ваше решение для домашней страницы блога. Спасибо.