Computer >> 컴퓨터 >  >> 프로그래밍 >> CSS

CSS로 채팅 메시지 UI 만드는 방법 – 말풍선부터 타임스탬프까지

CSS만으로도 실제 메신저 앱에서 볼 수 있는 것 같은 채팅 메시지 UI를 손쉽게 만들 수 있습니다. 말풍선 형태의 메시지 버블, 원형 프로필 이미지, 좌우로 배치되는 타임스탬프까지 모두 기본적인 CSS 속성만으로 구현할 수 있습니다. 아래 예제 코드를 통해 구체적인 방법을 살펴보겠습니다.

예제 코드

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
   body {
      margin: 0 auto;
      max-width: 800px;
      padding: 0 20px;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
   }
   .message {
      font-size: 18px;
      font-weight:500;
      border: 2px solid #dedede;
      background-color: #55e4a8;
      color:rgb(0, 0, 0);
      border-radius: 12px;
      padding: 10px;
      margin: 10px 0;
   }
   .darker {
      border-color: #ccc;
      background-color: rgb(111, 25, 182);
      color:white;
   }
   .message::after {
      content: "";
      clear: both;
      display: table;
   }
   .profilePic{
      width: 100%;
   }
   .message img {
      float: left;
      max-width: 60px;
      width: 100%;
      margin-right: 20px;
      border-radius: 50%;
   }
   .message img.right {
      float: right;
      margin-left: 20px;
      margin-right:0;
   }
   .timeStampRight {
      float: right;
      color: rgb(0, 0, 0);
      font-weight: bold;
   }
   .timeStampLeft {
      float: left;
      color: rgb(255, 255, 255);
      font-weight: bold;
   }
</style>
</head>
<body>
<h1>Chat Messages Example</h1>
<div class="message">
<img class="profilePic" src="https://i.picsum.photos/id/295/200/200.jpg">
<p>Hello. How are your holidays going?</p>
<span class="timeStampRight">9:00</span>
</div>
<div class="message darker">
<img class="profilePic" src="https://i.picsum.photos/id/255/200/200.jpg">
<p>They are going pretty good.Thanks for asking!</p>
<span class="timeStampLeft">9:05</span>
</div>
<div class="message">
<img class="profilePic" src="https://i.picsum.photos/id/295/200/200.jpg">
<p>Are you visiting somewhere in holidays?</p>
<span class="timeStampRight">9:07</span>
</div>
<div class="message darker">
<img class="profilePic" src="https://i.picsum.photos/id/255/200/200.jpg">
<p>Yes! Thinking of going to Disneyland.</p>
<span class="timeStampLeft">9:10</span>
</div>
</body>
</html>

코드 주요 포인트

  • .message 클래스가 각 채팅 말풍선의 기본 스타일을 담당합니다. border-radius로 부드러운 둥근 모서리를 만들고, paddingmargin으로 메시지 간 여백을 조절합니다.
  • .darker 클래스는 상대방의 메시지를 구분하기 위해 배경색과 글자색을 다르게 지정한 변형 스타일입니다.
  • .message imgborder-radius: 50%를 적용하면 프로필 이미지가 원형으로 표시됩니다.
  • .message::after의 clearfix 기법 덕분에 float된 이미지와 텍스트가 겹치지 않고 레이아웃이 올바르게 유지됩니다.
  • .timeStampRight / .timeStampLeft 클래스를 활용하면 메시지마다 전송 시간을 좌우로 배치할 수 있습니다.

실행 결과

위 코드를 브라우저에서 실행하면 다음과 같이 두 명이 주고받는 채팅 대화 화면이 출력됩니다.

CSS로 채팅 메시지 UI 만드는 방법 – 말풍선부터 타임스탬프까지