html (3)

💻 Programming/웹프로그래밍

[HTML] <fieldset> 태그

웹 상에서 설문지 페이지에 이용하기 좋은 fieldset 태그에 대해서 알아보겠습니다.

fieldset 태그는 form내에서 연관된 엘리먼트들을 그룹화할 때 사용합니다.

그리고 그렇게 그룹화된 엘리먼트들을 둘러싼 선을 그려줍니다.

아래처럼 말이죠

<fieldset> 태그를 활용한 설문지 예제

위 처럼 화면에 출력하려면 아래 코드를 이용하면 됩니다.

<form action="#">
  <fieldset>
      <legend>1. 좋아하는 색깔은?</legend>
      <input type="radio" id="blue" name="favorite-color"><label for="blue">파란색</label>
      <input type="radio" id="green" name="favorite-color"><label for="green">초록색</label>
      <input type="radio" id="red" name="favorite-color"><label for="red">빨간색</label>
    </fieldset>
    
    <p></p>
    
    <fieldset>
      <legend>2. 좋아하는 음식 종류는?</legend>
      <input type="radio" id="korean" name="food-type"><label for="korean">한식</label>
      <input type="radio" id="american" name="food-type"><label for="american">양식</label>
      <input type="radio" id="japanese" name="food-type"><label for="japanese">일식</label>
      <input type="radio" id="chinese" name="food-type"><label for="chinese">중식</label>
    </fieldset>
</form>

 

즉, legend 태그를 이용하여 타이틀을 넣어주고 input 이나 textarea와 같은 태그들을 이용해서 사용자의 입력을 받을 수 있도록 합니다.

위 코드에 하나의 필드셋을 더 추가하여 주관식 문항을 넣어보았습니다.

 

<fieldset> 태그를 활용한 설문지 예제

<form action="#">
    <fieldset>
      <legend>1. 좋아하는 색깔은?</legend>
      <input type="radio" id="blue" name="favorite-color"><label for="blue">파란색</label>
      <input type="radio" id="green" name="favorite-color"><label for="green">초록색</label>
      <input type="radio" id="red" name="favorite-color"><label for="red">빨간색</label>
    </fieldset>
    <p></p>
    <fieldset>
      <legend>2. 좋아하는 음식 종류는?</legend>
      <input type="radio" id="korean" name="food-type"><label for="korean">한식</label>
      <input type="radio" id="american" name="food-type"><label for="american">양식</label>
      <input type="radio" id="japanese" name="food-type"><label for="japanese">일식</label>
      <input type="radio" id="chinese" name="food-type"><label for="chinese">중식</label>
    </fieldset>
    <p></p>
    <fieldset>
      <legend>3. 탕수육은 어떻게 먹어야 맛있나요?</legend>
      <textarea placeholder="생각을 적어주세요."></textarea>
    </fieldset>
  </form>

 

fieldset 태그는 크롬, 파폭, 엣지, 오페라 등 대부분의 브라우저에서 지원하고 있으며 fieldset의 속성으로 disabled를 명시해주면 해당 필드셋 내의 엘리먼트들이 모두 비활성화 처리됩니다.

 

개인블로그 만들기 프로젝트하다가 알게된 새로운 태그라 기록용으로 포스팅해보았습니다.

 

 

참고문서: https://developer.mozilla.org/ko/docs/Web/HTML/Element/fieldset

 

둥근 토글 버튼

본 포스팅에서는 html, css, javascript를 이용하여 둥근 toggle버튼을 만들고, 버튼의 상태가 변경될 때마다 상태를 출력하는 기능까지 만들어 봅니다. 본 보스팅에 사용되는 기본코드는 w3schools에서 가지고 온 것입니다. w3schools에서는 단순히 css를 이용해서 토글버튼처럼 보이는 것을 만드는 것 까지만 보여주었는데, 저는 그렇게 토글이 될 때마다 자바스크립트를 이용해서 어떤 기능이 실행되는 부분까지 확장해서 포스팅합니다.

 

우선 toggle.html 파일에 input tag를 이용해서 아래와 같이 작성해줍니다.

<!DOCTYPE html>
<html>

<head>
</head>

<body>
    <label class="switch">
        <input type="checkbox" />
        <span class="slider round"></span>
    </label>
</body>

</html>

 

그리고 toggle.css 파일을 하나 만들어서 그 안에 아래와 같이 작성을 해줍니다.

/* 슬라이더 외부를 감싸는 라벨에 대한 스타일 */
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

/* HTML 기본 체크박스 숨기기 */
.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

/* 슬라이더 - 실제로 토글될 부분 */
.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* 슬라이더를 동그랗게 보여주기 위한 부분 */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}

 

이제 HTML 파일의 <head></head> 부분에 위 css 파일을 링크시켜줍니다.

<head>
	<link rel="stylesheet" type="text/css" href="toggle.css" />
</head>

 

이제 toggle.html 파일을 더블클릭해서 브라우저에서 열어보면 아래 영상처럼 움직이는 것을 확인할 수 있습니다.

 

둥근 토글 버튼 움직이는 영상

 

자, 이제 여기에 자바스크립트를 이용하여 기능을 추가해보도록 할건데요,

이 토글버튼은 input 태그의 checkbox를 이용한 것이므로 토글이 될 때마다 checked 속성이 변경되도록 되어있습니다.

이 기본적인 내용을 기억하고 자바스크립트에서 토글버튼의 checked 속성을 기반으로 특정 문자열을 출력하도록 해보겠습니다.

자바스크립트 파일은 따로 만들지 않고 그냥 html 파일에 추가하도록 할게요.

우선, input 태그에 onclick 속성을 이용하여 toggle이라는 함수를 호출하도록 하고, toggle 함수를 구현하겠습니다.

아래처럼 input  태그의 onclick 속성을 넣어주세요. 

<label class="switch">
    <input type="checkbox" onclick="toggle(this)">
    <span class="slider round"></span>
</label>

이렇게 해주면 토글버튼(체크박스)가 클릭될 때마다 toggle이라는 함수를 호출하면서 자기자신을 파라미터로 넘겨주게 됩니다.

 

자, 이제 body 아래쪽에 자바스크립트를 이용하여 스크립트를 작성해보겠습니다.

<script>
    function toggle(element) {
        console.log(element.checked);
    }
</script>

위 코드는 <head></head> 에 위치해도 되고 <body></body> 사이에 위치해도 됩니다.

당연히 별도 파일로 분리하여 작성해도 됩니다.

분리하여 작성하는 것과 관련해서는 제가 작성한 다른 포스트에서 확인 가능합니다. -> https://keichee.tistory.com/356

저는 <body></body> 사이에 넣어놓았습니다.

<body>
    <label class="switch">
        <input type="checkbox" onclick="toggle(this)">
        <span class="slider round"></span>
    </label>

    <script>
        function toggle(element) {
            console.log(element.checked);
        }
    </script>
</body>

 

자, 여기까지 html 파일 전체 코드가 어떻게 되는지 다시 한번 보여드릴게요.

<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" type="text/css" href="toggle.css" />
</head>

<body>
    <label class="switch">
        <input type="checkbox" onclick="toggle(this)">
        <span class="slider round"></span>
    </label>

    <script>
        function toggle(element) {
            console.log(element.checked);
        }
    </script>
</body>

</html>

 

여기까지 완성하여 실행하면 체크박스(토글버튼)을 클릭할 때마다 toggle함수가 실행되면서 현재 체크박스의 상태가 어떻게 바뀌었는지를 출력하게 됩니다.

확인을 위해서 브라우저에서 toggle.html 파일을 새로고침하여 다시 열어주시고,

화면에서 우클릭 > 검사 (inspect)를 선택하여 개발자도구(developer tools)를 열어서 console탭을 열어주세요.

그리고 버튼을 누를때마다 어떤 값이 출력이 되는지 확인해보도록 하겠습니다.

 

토글 버튼 동작 영상

 

자, 이렇게 자바스크립트를 이용해서 토글버튼의 상태값을 출력해보았습니다.

어떤가요? 별로 어렵지 않죠? css 스타일을 해석하기 힘드실 순 있겠으나, 여기서 그런 부분을 자세하게 다루진 않겠습니다.

좀 더 나아가서 토글버튼의 상태값에 따라 ajax 요청을 서버에 날려 실제 DB를 업데이트하거나, 

또는 html의 특정 element를 hide하거나 show하는 등의 기능을 만들어 보세요.

 

그럼 오늘도 즐거운 코딩하시길 바래요 ^-^

 

- 깐깐한 개발자 -

 

CSS를 HTML문서에서 사용하는 방법은 네가지가 있습니다. 그 중에서도 가장 많이 쓰이는 방법은 inline CSS와 External CSS.

1. Embedded CSS - The <style> Element:

 <style> 요소를 이용해서 <head>...</head> 태그 내에 삽입하는 방법입니다. 

<head>
<style type="text/css" media="...">
Style Rules
............
</style>
</head>

속성:

 <style> 태그 내의 속성과 값은 아래와 같습니다.

Attribute Value Description
type text/css Specifies the style sheet language as a content-type (MIME type). This is required attribute.
media screen
tty
tv
projection
handheld
print
braille
aural
all
Specifies the device the document will be displayed on. Default value is all. This is optional attribute.

예제:

<head>
<style type="text/css" media="all">
h1{
color: #36C;
}
</style>
</head>

2. Inline CSS - The style Attribute:

인라인 CSS는 그냥 html태그 안에다가 써넣는 것을 말합니다. 가장 일반적으로 이렇게 사용하죠. 그러다가 따로 분리해서 관리해야되는 스타일이 있다면 이 다음에 설명한 External CSS를 이용하시면 됩니다. 

<element style="...style rules....">

속성:

Attribute Value Description
style style rules The value of style attribute is a combination of style declarations separated by semicolon (;).

예제:

<h1 style ="color:#36C;"> This is inline CSS </h1>

 

적용된 결과는 아래와 같습니다. 

This is inline CSS

3. External CSS - The <link> Element:

 <link> 요소를 이용하여 HTML 문서에 외부에서 정의된 CSS파일을 링크시킬 수가 있습니다. 

간단한 문법을 한번 볼까요??

<head>
<link type="text/css" href="..." media="..." />
</head>

속성:

 <link> 태그의 속성과 속성값들 입니다. 

Attribute Value Description
type text/css Specifies the style sheet language as a content-type (MIME type). This attribute is required.
href URL Specifies the style sheet file having Style rules. This attribute is a required.
media screen
tty
tv
projection
handheld
print
braille
aural
all
Specifies the device the document will be displayed on. Default value is all. This is optional attribute.

예제:

간단하게 mystyle.css 를 만들어 봅시다.

h1, h2, h3 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}

 

이제 mystyle.css파일을 HTML문서에 링크를 시켜볼까요??

<head>
<link type="text/css" href="mystyle.css" media="all" />
</head>

4. Imported CSS - @import Rule:

@import 를 이용해서 <link> 요소처럼 스타일파일에 링크를 걸 수도 있습니다.  기본문법은 다음과 같습니다.

<head>
@import "URL";
</head>

 

아래처럼 url()메소드를 이용할 수도 있습니다.

<head>
@import url("URL");
</head>

예제:

<head>
@import "mystyle.css";
</head>

CSS Rules Overriding ( 규칙 오버라이딩 )

지금까지 CSS를 사용하는 네가지 방법에 대해서 알아보았습니다. 이 네가지 규칙이 동시에 적용이 된다면 어떤일이 벌어질까요??? 서로서로 오버라이딩을 하게 되는데 그 규칙을 한번 알아보도록 하겠습니다. 

  • inline 스타일이 다른 방법보다 항상 최우선시 적용됩니다.  

  • <style>...</style> 태그 내에 지정된 스타일들은 외부 CSS파일에 정의된 값들보다 우선권을 가집니다.

  • 외부 CSS파일은 항상 최저우선권을 가집니다. 

Handling old Browsers ( 구버전 브라우저 처리 )

구버전 브라우저 중에는 CSS를 지원하지 않는 브라우저가 있고 이런 브라우저를 사용하는 사용자들이 있을 수도 있겠죠. 만약 그럴경우에는 CSS를 적용하지 않도록 할 수 있습니다. 아래처럼 <!-- 와  --> 로 감싸서 말이죠. 

<style type="text/css">
<!--
body, td {
   color: blue;
}
-->
</style>

CSS Comments ( 주석 )

CSS에서 주석은 /* 주석처리 할 내용 */  이렇게 쓰시면 됩니다. 여러 줄에 걸쳐도 관계 없습니다. 

예제:

/* This is an external style sheet file */
h1, h2, h3 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}
/* end of 
style rules. */

 

 

 

 

 

 

Reference : http://www.tutorialspoint.com/css/css_inclusion.htm

 

 

 

 

 

 

'💻 Programming > CSS' 카테고리의 다른 글

[CSS] 6. Background ( 배경 설정 )  (0) 2016.06.12
[CSS] 5. Colors ( 색깔 )  (0) 2016.06.12
[CSS] 4. Units ( 단위 )  (0) 2016.06.12
[CSS] 2. Syntax ( 문법, 사용법 )  (0) 2016.06.12
[CSS] 1. CSS란 ?  (0) 2016.06.11