Как установить маржу или прокладку div на основе собственной высоты (когда родитель прокручивается)?CSS

Разбираемся в CSS
Ответить Пред. темаСлед. тема
Anonymous
 Как установить маржу или прокладку div на основе собственной высоты (когда родитель прокручивается)?

Сообщение Anonymous »

Я строю интерфейс чата, где последнее сообщение растет динамически (потоковой текст). Мне нужно это сообщение, чтобы оставаться выровненным с верхней частью контейнера для прокрутки по мере его роста.
Я придумал это плохое решение, где я рассчитываю (высота контейнера - высота сообщения) + 8px и устанавливаю его в виде поля, чтобы позволить некоторым прокладкам Scryk (избегая сообщения, чтобы натолкнуть на основание, когда текст является очень коротким). Динамическая заполнение/маржа на основе его собственного размера без расчетов javaScript QuerySelector и ручной высоты? Или какие-либо новые функции CSS (запросы контейнеров, позиционирование якоря и т. Д.), Которые могли бы решить это? class = "Snippet-Code-Html Lang-Html PrettyPrint-Override">

Код: Выделить всё





Minimal Chat Interface

body {
font-family: Arial, sans-serif;
margin: 20px;
background-color: #f5f5f5;
}

.container {
max-width: 500px;
margin: 0 auto;
}

.controls {
margin-bottom: 20px;
text-align: center;
}

.controls button {
padding: 10px 20px;
margin: 5px;
border: none;
border-radius: 8px;
background-color: #007bff;
color: white;
cursor: pointer;
}

.chat-container {
height: 400px;
border: 2px solid #333;
border-radius: 8px;
overflow-y: auto;
background-color: white;
position: relative;
}

/* Red reference line */
.chat-container::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 2px;
background-color: red;
z-index: 10;
}

.chat-messages {
padding: 20px;
display: flex;
flex-direction: column;
min-height: 100%;
}

.message {
margin-bottom: 12px;
padding: 12px 16px;
border-radius: 18px;
max-width: 70%;
line-height: 1.4;
}

.message.user {
background-color: #007bff;
color: white;
align-self: flex-end;
}

.message.assistant {
background-color: #f1f3f5;
color: #333;
align-self: flex-start;
}

.streaming-container {
flex-grow: 1;
display: flex;
flex-direction: column;
}

.streaming-message {
background-color: #f8f9fa;
color: #333;
padding: 16px;
border-radius: 18px;
border: 2px solid #007bff;
max-width: 85%;
align-self: flex-start;
line-height: 1.5;
}






Add More Text
Remove Text
Reset



Hey there! How are you doing?
Hello! I'm doing great, thank you for asking.
Can you explain how this works?




I'd be happy to explain! This is a streaming message...







let textLevel = 1;
const baseText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit";
const loremTexts = [
", sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
" Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris.",
" Nisi ut aliquip ex ea commodo consequat.  Duis aute irure dolor in reprehenderit.",
" In voluptate velit esse cillum dolore eu fugiat nulla pariatur.",
" Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia.",
" Deserunt mollit anim id est laborum. Sed ut perspiciatis unde omnis iste natus.",
" Error sit voluptatem accusantium doloremque laudantium, totam rem aperiam.",
" Eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae.",
" Dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur.",
" Aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione."
];

function getLoremText() {
let fullText = baseText;
for (let i = 0; i < textLevel; i++) {
fullText += loremTexts[i % loremTexts.length];
}
return fullText;
}

function adjustPadding() {
const container = document.getElementById('container');
const lastAssistantMessage = document.getElementById('streaming');

const containerHeight = container.clientHeight;
const messageHeight = lastAssistantMessage.offsetHeight;

const marginBottom = (containerHeight - messageHeight) + (8);
lastAssistantMessage.style.marginBottom = marginBottom + 'px';
}

function updateStreamingMessage() {
document.getElementById('streaming').textContent = getLoremText();
adjustPadding();
}

function addText() {
textLevel++;
updateStreamingMessage();
}

function removeText() {
if (textLevel > 1) {
textLevel--;
updateStreamingMessage();
}
}

function resetText() {
textLevel = 1;
updateStreamingMessage();
}

function scrollToAlignment() {
const container = document.getElementById('container');
const streamingMessage = document.getElementById('streaming');

// Scroll so streaming message top aligns with the red line
const messageTopInContainer = streamingMessage.offsetTop - container.offsetTop;
const targetScrollTop = messageTopInContainer - 22; // Account for padding + red line

container.scrollTop = targetScrollTop;
}

// Initialize - only scroll on initial load
updateStreamingMessage();

// Initial scroll to alignment after page loads (only once)
window.addEventListener('load', () => {
setTimeout(scrollToAlignment, 100);
});





Подробнее здесь: https://stackoverflow.com/questions/797 ... ent-is-a-s
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «CSS»