상세 컨텐츠

본문 제목

Tailwind CSS Tip.] CSS Flex 의 중앙 정렬

ChatGPT 형님이 알려줌

by With AI Life 2024. 7. 22. 22:03

본문

* 이 글은 ChatGPT를 이용하여 작성하였고, 블로그 게시를 위하여 편집하였습니다.

Prompt : tailwind css flex contents 중앙정렬하는 방법에 대하여 알려줘

Answer:

Tailwind CSS를 사용하여 flex 컨테이너 내의 내용을 중앙 정렬하려면 justify-center와 items-center 유틸리티 클래스를 사용하면 됩니다. 다음은 세로 및 가로로 중앙 정렬하는 예제입니다.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Centering with Tailwind CSS</title>
    <link
        href="[https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css](https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css)"
        rel="stylesheet">
</head>

<body class="h-screen bg-gray-100">
    <div class="flex justify-center items-center h-full">
        <div class="p-8 bg-white shadow-md rounded">
            <p class="text-lg">This content is centered!</p>
        </div>
    </div>
</body>

</html>

위 예제에서는 flex, justify-center, items-center 클래스를 사용하여 컨테이너 내의 내용을 세로 및 가로 중앙에 정렬합니다. h-screen 클래스는 화면 전체 높이를 설정하고, h-full 클래스는 부모의 전체 높이를 상속받습니다.

여기서 중요한 클래스는 다음과 같습니다:

  • flex: 요소를 플렉스 컨테이너로 만듭니다.
  • justify-center: 자식 요소들을 가로축 중앙으로 정렬합니다.
  • items-center: 자식 요소들을 세로축 중앙으로 정렬합니다.
  • h-full: 부모 요소의 전체 높이를 상속받아 컨테이너가 화면의 전체 높이를 차지하도록 합니다.

이렇게 하면 컨테이너 내의 내용이 중앙에 배치됩니다. 필요에 따라 다른 Tailwind CSS 유틸리티 클래스를 추가하여 스타일을 조정할 수 있습니다.

관련글 더보기