Css высота блока изменяемая

CSS — Плавное изменение высоты в зависимости от содержимого

У меня есть div , внутри которого изменяются разделы. Разделы имеют разную высоту. При переходе от одного к другому высота div должна изменяться плавно. Пробовал ставить transition на div . Дополнение: Я делаю на Angular. Внутри div стоит router-outlet . При переходе с одной страницы на другую его содержимое меняется. Изменяется и высота. Как сделать изменение высоты плавным, как если бы оно было со свойством transition ?

Нет, я делаю на Angular. Внутри div стоит . Это тэг, содержимое которого меняется в зависимости от пути (url).

я не докапался а просто изначально вопрос кажется из рубрики css а на самом деле это касается angular

2 ответа 2

вам придется находить скриптом исходное и конечное значение высоты div или router-outlet и проставлять их соответствующему элементу на лету — только тогда transition отработает. Браузер вычисляет все промежуточные значения свойств, на которые действует transition, ориентируясь на их начальное и конечное значения. А оных значений у элементов с неизвестными заранее свойствами (в вашем случае — чему равна height , если она auto ?), разумеется, нет.

другим способом — это с JS. имхо, самый оптимальный вариант — как я уже написал, скриптом проставлять высоту, а уж плавный переход предоставить браузеру с работающим transition . Минус тут только один: рассчитать высоту блока с заранее неизвестным количеством контента, да еще и в зависимости от размеров окна браузера — та еще задача.

Читайте также:  Css div display type

А что, если на блок, который должен меняться по высоте, повесить сабтри мутэйшен обсервер . Ему самому задать фиксированную высоту и оверфлоу хиден , а при изменении контента, задавать высоту равную высоте контента дочернего элемента?

Вы хотели что-то типа такого?

*, *:before, *:after < -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; margin: 0; padding: 0; >body < position: relative; >#content < max-width: 300px; margin: 0 auto; overflow: hidden; position: relative; margin-top: 10px; >#content::before < display: block; content: ''; position: absolute; width: 100%; height: 100%; background-color: rgba(255, 255, 255); transition: transform 0.3s ease-in-out; transform: translateY(100%); >#btn < display: flex; justify-content: center; align-items: center; position: absolute; left: 0; top: 0; width: 50px; height: 50px; background-color: black; color: white; cursor: pointer; >#content.active::before
 
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Exercitationem, sunt incidunt quos eligendi in esse iure eum quam aperiam nulla vero delectus sequi ipsam aut sit modi distinctio corrupti dolor? Lorem ipsum, dolor sit amet consectetur adipisicing elit. Exercitationem, sunt incidunt quos eligendi in esse iure eum quam aperiam nulla vero delectus sequi ipsam aut sit modi distinctio corrupti dolor?
Клик

Можно, конечно, менять высоту, но это плохо анимировать height , width , margin , padding : браузер перерисовывает страницу, когда мы анимируем эти свойства, это затратно по производительности

content.style.height = content.scrollHeight + 'px'; btn.addEventListener('click', () => < const height = content.scrollHeight; content.classList.toggle('active'); if (content.classList.contains('active')) < content.style.height = '0px'; >else < content.style.height = height + 'px'; >>); const ipsum = ' Lorem ipsum, dolor sit amet consectetur adipisicing elit.'; input.addEventListener('input', (e) => < const value = e.target.value; if (value >9) return false; // чтобы нельзя было большие куски просто вводить в блок for (let i = 0; i < value; i++) < content.innerHTML += ipsum; >content.style.height = content.scrollHeight + 'px'; >);
*, *:before, *:after < -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; margin: 0; padding: 0; >body < position: relative; >#btn < display: flex; justify-content: center; align-items: center; position: absolute; left: 0; top: 0; width: 50px; height: 50px; background-color: black; color: white; cursor: pointer; >#content < max-width: 300px; margin: 0 auto; margin-top: 10px; overflow: hidden; transition: height 0.3s ease-in-out; >#input
 
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Exercitationem, sunt incidunt quos eligendi in esse iure eum quam aperiam nulla vero delectus sequi ipsam aut sit modi distinctio corrupti dolor? Lorem ipsum, dolor sit amet consectetur adipisicing elit. Exercitationem, sunt incidunt quos eligendi in esse iure eum quam aperiam nulla vero delectus sequi ipsam aut sit modi distinctio corrupti dolor?
Клик

Источник

Плавное изменение высоты блока на CSS

Рассмотрим способ решения проблемы сворачивания и разворачивания блока неизвестной высоты на чистом CSS. Это распространённая задача, которая часто вызывает трудности в реализации, когда значение свойства «height» не задано явно, а находится в состоянии «auto».

Для начала посмотрите как работает решение на практике:

Принцип работы

Обычная реализация подразумевает знание начальной и конечной высоты блока. Чтобы обойти это ограничение, будем использовать свойство «max-height». Для свёрнутого значения оно будет нулевым, а для открытого — максимально большим. В нашем случае точно хватит 1000 пикселей.

Стиль блока в раскрытом состоянии:

Свёрнутое состояние будет происходить за счёт добавления класса «expansion-hide».

  • В развёрнутом виде у «DIV» будет класс «expansion-body».
  • В свёрнутом — «expansion-body expansion-hide».

Плавное сворачивание и разворачивание достигается с помощью нелинейной трансформации максимальной высоты. Значение от 1000 до 0 меняется сначала очень быстро, а потом резко замедляется. Это сглаживает анимацию, если высота блока намного меньше 1000 пикселей. При обычной линейной трансформации при сворачивании была бы задержка.

Описанный способ легко адаптируется для плавного изменения ширины путём применения свойства «max-width».

Добавление класса и возможные проблемы

Для добавления и удаления класса «expansion-hide» в примере использовался чистый JS. Он не влияет на сам процесс анимации. В обработчике «onclick» всего одна строка кода.

document.getElementById('expansion-body').classList.toggle('expansion-hide')

Сама html-разметка также проста:

Небольшое предупреждение — не добавляйте к блоку отступы «padding», иначе он не будет до конца закрываться. Если они нужны, то создайте внутри ещё один «div» и добавляйте произвольные стили к нему.

PS Чтобы поблагодарить за решение напишите любой комментарий.

Источник

Using CSS Transitions on the Height Property

Little effects on our web pages can make a lot of difference on the user experience of a website. When the state of an element is changed, it’s pretty cool to have a visual effect to show that an action occurred. Thanks to CSS transitions, we have a wide range of transition effects that can be used on our HTML elements. The height of an element is one CSS property that often needs to be transitioned. Sometimes, we want a part of an element to be collapsed until it is needed. That is, when a button is clicked, the height of an element increases or decreases. See more buttons and bootstrap panels make use of this technique. Transition effects come with some frameworks like Bootstrap and JQuery. Yet, CSS transitions give you a whole lot of flexibility in transitioning the height. Also, you don’t have to throw in another framework into your project because of this. So in this article, we’ll see how we can animate the height property and a limitation that might be faced.

Transitioning the Height

We’ll be using a simple example to explain this. We have an article that we will collapse at first. Clicking on a see more button will increase the height of the element to show all the contents of the article. We will create a CSS class for this. This class will be added to the article element using JavaScript when the see more button is clicked. So first, we’ll add an article element to an HTML file.

  id="article"> Why You Should Care about the Ipsum Tart jelly beans croissant toffee oat cake soufflé gingerbread. Toffee powder cheesecake soufflé bonbon tiramisu toffee powder gummi bears. Toffee tootsie roll powder soufflé apple pie. Fruitcake fruitcake soufflé sweet oat cake cotton candy lemon drops biscuit. Chupa chups fruitcake dessert icing halvah oat cake. Lollipop candy canes halvah bonbon marshmallow croissant. Wafer chupa chups cotton candy tart pudding pie cupcake. Candy canes gummies macaroon pudding cupcake cupcake pudding jujubes. Donut halvah pie chocolate. Sugar plum dessert pudding icing jelly-o cake. Gingerbread macaroon wafer. Caramels muffin jelly wafer carrot cake. Marshmallow candy cookie danish cake. Cupcake croissant gummi bears pastry wafer. Macaroon croissant bonbon wafer. Topping fruitcake topping biscuit. Tiramisu powder sesame snaps candy. Dessert donut cookie carrot cake dragée muffin. Lollipop oat cake cookie candy canes fruitcake. Candy croissant candy canes croissant bear claw cake brownie biscuit pie. Liquorice wafer wafer cookie lollipop gingerbread chocolate cake oat cake dessert. Pudding gingerbread croissant cheesecake soufflé. Muffin gummies chocolate chocolate cupcake pastry. Sweet roll fruitcake bear claw sweet caramels lemon drops lemon drops. Pie sesame snaps cupcake macaroon bonbon oat cake ice cream oat cake topping. Brownie dessert toffee brownie jelly-o chocolate jujubes halvah chocolate bar. Pudding gingerbread dessert. Bear claw tiramisu gummies pudding. Toffee marshmallow jelly beans pie marzipan caramels ice cream lollipop powder. Dragée sesame snaps sugar plum. Marshmallow sweet roll croissant tootsie roll icing. Dragée chocolate marzipan jelly cotton candy. Jujubes sweet chocolate bar candy sweet roll lollipop biscuit dessert. Danish lollipop caramels toffee pastry. Wafer candy canes cupcake chupa chups gummies lemon drops jujubes powder. Caramels danish marshmallow gummies. Jujubes muffin danish pie icing brownie. Toffee sweet tiramisu topping. Cookie fruitcake icing jelly-o sesame snaps. Caramels gingerbread ice cream pastry donut. Gummies liquorice carrot cake sesame snaps muffin toffee dragée marzipan oat cake. Chocolate bar lemon drops dessert. Sweet cupcake sesame snaps carrot cake dessert candy canes halvah tart ice cream. Jelly donut chocolate bar chupa chups tootsie roll soufflé carrot cake tootsie roll gummi bears. Pastry jujubes soufflé marshmallow toffee. Macaroon marshmallow oat cake jujubes caramels topping marzipan cupcake icing. Brownie jelly sweet tootsie roll brownie jujubes cupcake pie. Cookie lollipop ice cream tiramisu jelly-o chocolate gummies. Tart biscuit tiramisu biscuit cake tart danish topping cookie. Liquorice donut dragée tart. Dragée soufflé pudding halvah cookie marshmallow jujubes sweet roll. Pastry chocolate tiramisu bonbon jelly beans lollipop marshmallow chocolate cake. Icing carrot cake gummies cheesecake dragée. Cake fruitcake gummies. Halvah jujubes toffee pudding bonbon soufflé brownie cupcake candy. Icing biscuit cake jujubes. Chocolate bar candy canes caramels cupcake.   id="seeMoreBtn">See More  
 article  max-width: 800px; height: 300px; overflow-y: hidden; > /* This class is added when button is clicked */ article.expanded  height: 628px; > button  height: 41px; padding: 0 2rem; > 
 const seeMore = document.getElementById("seeMoreBtn"); const article = document.getElementById("article"); seeMore.addEventListener("click", () =>  article.classList.toggle("expanded"); const expanded = article.classList.contains("expanded"); if (expanded)  seeMore.innerHTML = "See Less"; > else  seeMore.innerHTML = "See More"; > >); 

Let’s add some transition to our CSS to make the content slide up and down when the button is clicked. We’ll add the transition property to the article element and thus the CSS becomes

 article  max-width: 800px; height: 300px; overflow-y: hidden; transition: height 0.4s linear; > 

And now the article slides up and down. You might think this is the part I say thank you for reading this article. No, it’s not. There is a limitation that arises with this method. Let’s consider it.

The Limitation

What we did above works well when the height of the article is known. What happens though when the height of the element is unknown? For instance, when dealing with dynamic content? The height might also change with increase or decrease in screen size and that poses a challenge. For dynamic content, the height of an element should be set to auto . This way, any increase or decrease in the height of the element will be accomodated. Here’s the challenge: CSS transition does not work when the height of an element is set to auto. Here’s what you’ll get. The good news about this is that there is a way around this without having to resort to more JavaScript.

The Solution

The hack is to transition the max-height property instead of the height property. First, we have to estimate the greatest height our element can ever get. We then set the element to have max-height greater than our estimate when the element is expanded. So let’s revisit our CSS again. This time we’ll change our height properties to max-height .

 article  max-width: 800px; max-height: 300px; overflow-y: hidden; /*Transition time is increased to accomodate the height */ transition: max-height 0.7s linear; > article.expanded  max-height: 1500px; > 

This way the animation works and we still get the effect we want. The transition time might have to be adjusted depending on the effect you want. Got any question or addition? Please leave a comment. Thank you for reading 🙂

Источник

Оцените статью