본문 바로가기
HTML/CSS

[ HTML / CSS ] ::after, ::before 사용해보기

by teamnova 2022. 11. 2.

안녕하세요 오늘은 css 의 가상요소(pseudo-element)인 ::after 과 ::before 에 대해 알아보겠습니다.

 

CSS 가상 요소는 선택자로 선택한 요소의 뒤에 붙여 표기하는 미리 약속된 키워드를 말합니다. 요소의 특정한 부분에 정해진 기능을 하도록 가상 요소 키워드 별로 미리 기능이 정의되어 있으며, 요소에 CSS 속성을 적용하는 것과 같은 방법으로 다양한 CSS 속성을 적용할 수 있기 때문에 마치 하나의 하위 요소처럼 사용할 수 있어서 가상 요소(pseudo-element)라고 합니다.

 

그리고 ::after, ::before 는 내용의 앞과 뒤에 컨텐츠를 추가할 때 사용하면 유용한 가상요소입니다. 이 컨텐츠는 content 라는 속성에서 정의할 수 있습니다.

 

바로 예제로 넘어가겠습니다.

 

구현 화면은 다음과 같습니다.

 

전체코드는 다음과 같습니다.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>::before and ::after</title>
    <style>
        body {
            margin-top: 14rem;
            margin-left: 14rem;
        }

        table {
            border-collapse: collapse;
        }

        td, th {
            text-align: left;
            padding-right: 30px;
            padding-top: 6px;
            padding-bottom: 6px;
            border-bottom: 1px solid rgb(214, 214, 214);
        }

        th {
            background-color: aliceblue;
            text-align: center;
        }

        .title::after {
            content: '  new';
            color: blue;
        }

        .popular::before {
            content: 'HOT';
            color: white;
            background-color: red;
            margin-right: 10px;
            border-radius: 4px;
            font-size: small;
            padding: 2px;
        }
    </style>
</head>
<body>

    <table>
        <tr>
            <th>번호</th>
            <th>제목</th>
            <th>작성자</th>
            <th>작성일</th>
            <th>조회수</th>
        </tr>
        <tr>
            <td>185</td>
            <td class="title popular">오늘 비가 많이 오네요...</td>
            <td>구름러버</td>
            <td>22.08.08</td>
            <td>41</td>
        </tr>
        <tr>
            <td>184</td>
            <td class="title">혹시 여기 식당 가보신 분 계신가요???</td>
            <td>맛집뿌셔뿌셔</td>
            <td>22.08.06</td>
            <td>8</td>
        </tr>
        <tr>
            <td>183</td>
            <td class="title">맛저하세요~ 저는 라면에 맥주한병 ㅋㅋ</td>
            <td>맛집뿌셔뿌셔</td>
            <td>22.08.04</td>
            <td>15</td>
        </tr>
    </table>

    <script>

    </script>
</body>
</html>