
아래의 그림과 같이 프로필 이미지와 이름을 가로로 배치하고, 이미지 오른쪽 아래에 초록색 상태 표시 뱃지를 붙이는 프로필을 만들어 보았다.
단순히 따라 만드는 게 아니라,
만들면서 헷갈렸던 부분들을 정리해보려고 한다.
초록 원을 만들고 border 를 흰색으로 주면
'흰 원 + 초록 원'처럼 보인다.
.user-status {
width: 12px;
height: 12px;
border-radius: 50%;
border: 2px solid #fff;
background-color: #21D891;
}
초록 원은 이미지 위에 겹쳐서 특정 위치에 딱 붙여야 했다.
그래서 position: absolute 를 사용했다.
absolute 는 static이 아닌 조상을 기준으로 위치를 잡는다..user-photo 에 position: relative 를 준다..user-photo {
position: relative;
}
.user-status {
position: absolute;
right: -2px;
bottom: -2px;
}
<img> 는 기본적으로 inline 요소라서 아래쪽에 보이지 않는 여백이 포함된다.
그래서 위치 계산이 그 여백까지 포함되어 초록 원이 살짝 아래로 밀려 보일 수 있다.
→ <img> 를 display: block; 으로 바꾸면
이미지가 딱 실제 높이만 차지해서, 원이 의도한 위치에 붙는다.
.user-photo img {
display: block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Position 1</title>
<link href="https://fonts.googleapis.com/css?family=Lato&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<div class="user-card">
<div class="user-photo">
<img src="./assets/user.jpg" alt="Bellogyoon" />
<span class="user-status" aria-label="Active"></span>
</div>
<h1 class="user-name">
Bellogyoon
</h1>
</div>
</body>
</html>
* {
box-sizing: border-box;
margin: 0;
}
body {
font-family: "Lato", sans-serif;
background-color: black;
}
h1 {
font-size: 16px;
font-weight: 400;
line-height: 1.5;
color: #273444;
}
.user-card {
width: 240px;
padding: 8px 12px;
border: 1px solid #E5EAEF;
border-radius: 4px;
background-color: white;
}
.user-card::after {
content: '';
display: block;
clear: left;
}
.user-photo, .user-name {
float: left;
}
.user-photo {
position: relative;
margin-right: 12px;
}
.user-photo img {
display: block;
width: 40px;
height: 40px;
border-radius: 50%;
}
.user-status {
position: absolute;
right: -2px;
bottom: -2px;
width: 12px;
height: 12px;
border-radius: 50%;
border: 2px solid #fff;
background-color: #21D891;
}
.user-name {
padding: 8px 0;
}
✔ 흰 원 + 초록 원은 '원 2개'가 아니라 border 로 더 간단하게 만들 수 있다.
✔ <img>는 기본적으로 inline 이라 베이스라인 여백 때문에 위치가 어긋나 보일 수 있다. → 습관처럼 display: block 하기
✔ 겹쳐서 배치해야 할 때는 position: absolute + 기준점 position: relative 조합이 핵심이다.