CSS를 활용하면 화면 크기에 맞춰 레이아웃이 자동으로 조정되는 반응형 폼(양식)을 손쉽게 만들 수 있습니다. 이 글에서는 Flexbox와 미디어 쿼리(@media)를 활용해 회원가입 형태의 반응형 폼을 구현하는 방법을 예제 코드와 함께 살펴보겠습니다.
핵심 구현 포인트
- box-sizing: border-box — 패딩과 테두리까지 요소의 전체 크기에 포함시켜 화면이 줄어들어도 레이아웃이 깨지지 않도록 합니다.
- display: flex + flex-wrap — 입력 필드들을 유연하게 배치하고, 공간이 부족해지면 자동으로 줄바꿈됩니다.
- @media 쿼리 — 화면 너비가 657px 이하로 좁아지면 flex-direction: column-reverse가 적용되어 필드들이 세로 방향으로 재배치됩니다.
- width: 100% — 입력창과 제출 버튼이 컨테이너 너비에 꽉 차게 확장되어 모바일에서도 사용성이 좋아집니다.
예제 코드
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
font-family: Arial;
font-size: 17px;
padding: 8px;
}
* {
box-sizing: border-box;
}
.Fields {
display: flex;
flex-wrap: wrap;
padding: 20px;
justify-content: space-around;
}
.Fields div {
margin-right: 10px;
}
label {
margin: 15px;
}
.formContainer {
margin: 10px;
background-color: #efffc9;
padding: 5px 20px 15px 20px;
border: 1px solid rgb(191, 246, 250);
border-radius: 3px;
}
input[type="text"] {
display: inline-block;
width: 100%;
margin-bottom: 20px;
padding: 12px;
border: 1px solid #ccc;
border-radius: 3px;
}
label {
margin-left: 20px;
display: block;
}
.icon-formContainer {
margin-bottom: 20px;
padding: 7px 0;
font-size: 24px;
}
.checkout {
background-color: #4caf50;
color: white;
padding: 12px;
margin: 10px 0;
border: none;
width: 100%;
border-radius: 3px;
cursor: pointer;
font-size: 17px;
}
.checkout:hover {
background-color: #45a049;
}
a {
color: black;
}
span.price {
float: right;
color: grey;
}
@media (max-width: 657px) {
.Fields {
flex-direction: column-reverse;
}
}
</style>
</head>
<body>
<h1 style="text-align: center;">Responsive Form Example</h1>
<div class="Fields">
<div>
<div class="formContainer">
<form>
<div class="Fields">
<div>
<h3>Register</h3>
<label for="fname">Full Name</label>
<input type="text" id="fname" name="firstname" />
<label for="email"> Email</label>
<input type="text" id="email" name="email" />
<label for="adr"> Address</label>
<input type="text" id="adr" name="address" />
</div>
<div>
<h3>Account Details</h3>
<label for="uname">Username</label>
<input type="text" id="uname" name="cardname" />
<label for="pass">Password</label>
<input type="text" id="pass" name="cardnumber" />
<div class="Fields">
<div>
<label for="accountAge">Account Age</label>
<input type="text" id="accountAge" name="accountAge" />
</div>
<div>
<label for="cvv">Security Question</label>
<input type="text" id="cvv" name="cvv" />
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
출력 결과
위 코드를 실행하면 데스크톱처럼 화면이 넓은 환경에서는 각 섹션이 가로로 나란히 배치된 다음과 같은 결과가 나타납니다.

반면, 스마트폰처럼 화면 크기가 좁아지면 미디어 쿼리가 작동하여 콘텐츠가 아래와 같이 세로 방향으로 자동 재배치됩니다.

마무리
이처럼 Flexbox와 미디어 쿼리만 활용해도 별도의 프레임워크 없이 다양한 기기에 대응하는 반응형 폼을 만들 수 있습니다. 실무에서는 여기에 required, placeholder 같은 HTML5 속성이나 입력값 유효성 검사를 추가하면 더욱 완성도 높은 폼을 구현할 수 있습니다.