Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript로 위치 지정 요소의 right 위치 설정하기

요소의 오른쪽(right) 위치를 설정하려면 JavaScript에서 right 속성을 사용하면 됩니다. right 속성은 위치 지정(positioned)된 요소가 기준이 되는 컨테이닝 블록의 오른쪽 가장자리에서 얼마나 떨어져 있을지를 결정합니다.

right 속성 사용 시 주의사항

right 속성이 정상적으로 동작하려면 해당 요소에 position 속성(absolute, fixed, relative 등)이 반드시 지정되어 있어야 합니다. position 값이 static인 요소에는 right 속성이 적용되지 않습니다.

예제

아래 예제에서는 버튼을 클릭하면 display() 함수가 호출되어 orange 배경의 div 요소 오른쪽 위치가 70px로 변경됩니다. 직접 실행해 결과를 확인해 보세요.

<!DOCTYPE html>
<html>
   <head>
      <style>
         #box {
            width: 350px;
            height: 200px;
            background-color: orange;
            border: 3px solid red;
            position: absolute;
         }
      </style>
   </head>

   <body>
      <p>버튼을 클릭하여 오른쪽 위치를 설정해 보세요.</p>
      <button type = "button" onclick = "display()"> 오른쪽 위치 설정 </button>
      <div id="box">
         <p>This is a div. This is a div. This is a div. This is a div.<p>
         <p>This is a div. This is a div. This is a div. This is a div.<p>
         <p>This is a div. This is a div. This is a div. This is a div.<p>
      </div>
      <br>

      <br>
      <script>
         function display() {
            document.getElementById("box").style.right = "70px";
         }
      </script>
   </body>
</html>

코드 설명

핵심 코드는 다음 한 줄입니다.

document.getElementById("box").style.right = "70px";

getElementById()로 id가 "box"인 요소를 가져온 후, style 객체의 right 속성에 "70px" 값을 할당합니다. 그러면 해당 요소는 화면 오른쪽 가장자리에서 70px만큼 떨어진 위치로 이동하게 됩니다. 이처럼 JavaScript의 style 객체를 활용하면 CSS 속성을 동적으로 변경하여 요소의 위치를 자유롭게 조절할 수 있습니다.