코딩 기록들

[FrontEnd] 9. Position, Background 본문

FrontEnd Programming

[FrontEnd] 9. Position, Background

코딩펭귄 2024. 3. 8. 17:09

Position

-  floating 보다는 좀더 세밀하고 정확하게 배치할 수 있는 방법

- 총 4개의 좌표가 있고, 해당 좌표에 배치를 하는 것.

- 배치하는 방법에 따라 4가지로 구분 : relative, fixed, absolute, sticky (static은 기본값. 아무런 효과없음)

- static : 정상적 흐름 : html을 작성한 순서

- relative : 상대배치 : element를 작성한 위치를 기준으로 'top, left, right, bottom' 좌표가 만들어짐, 가장많이 씀

- fixed : element를 (스크롤을 하더라도)항상 같은 위치에 배치시킴

- absolute : 절대적인 위치를 지정해줌. -> 문서 내에서 절대적인 위치 지정. 개인쇼핑몰에서 배송일정 팝업 띄울때 사용(position absoulte)

 

 

position: static;  (default)

문서의 흐름 : 위 -> 아래

 

 

 

position: absolute;

- viewport(보이는 브라우저 화면) 에서 화면에 위치함

 

- div를 기준으로 배치하는것이 아닌, div의 부모를 기준으로 배치가 되는것임!

 

 

position: relative;

- relative 가 적용된 엘리먼트 내부에서 좌표계가 0부터 다시 시작 (상대적 좌표가 생성됨)

position: fixed;

- 스크롤을 움직이더라도 항상 같은 위치에 표현된다.

- 고정위치 메뉴(전체메뉴, 누르면 제일위로/아래로 가기), Floating Menu, Floating Button 등을 만들 때 사용

- 회사를 상대로 만드는 enterprise application의 모든 레이아웃이 대부분 해당됨

 

 

position: sticky;

- 정상적인 Document flow로 자리잡고 있다가 스크롤이 움직일 때, 지정한 위치에 도달할 경우, Fixed 처럼 동작

- Header, Scroll-Spy 등에서 주로 사용

시도해보기) https://developer.mozilla.org/ko/docs/Web/CSS/position#

 

container stacking : 코드의 순서에 따라 박스가 겹치게 되는것 

--> z-index:2  사용하기(z-index는 1이 기본값)

 

position을 활용한 레이아웃 만들기 (position-fixed 예시이미지와 같이)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>W3Schools</title>
    <link rel="stylesheet" href="./styles/common.css">
</head>
<body>
    <div class="main-menu"></div>
    <div class="aside-menu">
        <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
            <li>6</li>
            <li>7</li>
            <li>8</li>
            <li>9</li>
            <li>10</li>
        </ul>
    </div>
    <div class="container">
        <h1>What is Lorem Ipsum?</h1>
        <p>
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum
        </p>
        <h1>Why do we use it?</h1>
        <p>
            It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
        </p>
        <h1>Where does it come from?</h1>
        <p>
            Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.
            The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.
        </p>
        <h1>Where can I get some?</h1>
        <p>
            There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
        </p>

    </div>

</body>
</html>
body{
    margin: 110px 0 0 210px;
}

.main-menu{
    /*위치고정용*/
    position: fixed;
    top:0;
    left:0;
    right:0;
    height: 100px;
    background-color: #000;
    margin:0;
    padding:0;
    z-index:2;
}

.aside-menu{
    position: fixed;
    top:100px; /*margin-top:100px; 해도 결과는 동일*/ 
    left:0;
    bottom: 0;
    width: 200px;
    background-color: #888;
    margin: 0;
    padding:0;
    /* 흘러넘치면 어떻게 처리할것인지 : overflow 
            -> 사이즈가 작아서 흘러넘치게되면 스크롤바 생김*/
    overflow: auto;
}

.container{
    background-color: #DDD;
   
    /* width: 100%; */
}

.container h1{
    position: sticky;
    /* 멈춰야 하는 곳 */
    top: 100px;
    background-color: #DDD;
    padding-top: 10px;
}

 

 

예시2)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>이미지 배치 연습</title>
    <link rel="stylesheet" href="./styles/image_container.css">
</head>
<body>
    <div>
        <div class="images">
            <img src="https://www.cnet.com/a/img/resize/69256d2623afcbaa911f08edc45fb2d3f6a8e172/hub/2023/02/03/afedd3ee-671d-4189-bf39-4f312248fb27/gettyimages-1042132904.jpg?auto=webp&fit=crop&height=675&width=1200" 
            alt="음식1" />
            <div>음식1 입니다.</div>
        </div>

        <div class="images">
            <img src="https://a.cdn-hotels.com/gdcs/production0/d1513/35c1c89e-408c-4449-9abe-f109068f40c0.jpg?impolicy=fcrop&w=800&h=533&q=medium"
            alt="음식2" />
            <div>음식2 입니다.</div>
        </div>

        <div class= "images">
            <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTGUzjwLga-iyGteS_dpwt9ApaVI17VV6X5xw&usqp=CAU" 
            alt="음식3" />
            <div>음식3 입니다.</div>
        </div>
    </div>
</body>
</html>
.images {
    display : inline-block;
    position: relative;
}

img {
    width: 400px;
    height: 350px;
}

/* images안에있는 div들을 대상으로 하겠다 */
.images div{
    position: absolute;
    background-color: #FFFA;
    bottom: 4px;
    width: 100%;
    height: 30%;
    padding-top: 16px;
    text-align: center;
}

 

 

 

 


 

Background

- Box Element 배경색이나 배경이미지를 설정

https://developer.mozilla.org/ko/docs/Web/CSS/background   |   https://www.w3schools.com/css/css_background.asp

[ 주요 속성 ]

- background-color: 배경색 지정

- background-image: 배경이미지 지정

- background-position: 배경이미지의 위치 지정 (background이미지의 '좌표'를 설정해주는것)

    -> Sprite 이미지로 배경이미지를 표현할 수 있다.

- background-repeat: 배경이미지 반복여부 지정

- background-size: 배경이미지의 크기 지정

- background (Shothand) -> 규칙이 까다롭다

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>background 실습</title>
    <link rel="stylesheet" href="./styles/background.css">
</head>
<body>
    <h1>백그라운드 실습페이지 입니다.</h1>
</body>
</html>
body{
    background-color: #000;
    background-image: url("../assets/foodbackground.jpg");
    background-repeat: no-repeat;
    background-repeat: repeat-x; /*x축으로만 반복*/
    background-repeat: repeat-y; /*y축으로만 반복*/
    background-position: center;
    /* background-position: 10px 50px; --> 단, 음수값을 넣으면 좌측상단 모서리쪽으로 이미지 넘어감*/
}

h1{
    background-color: #FFF4;
    color: #333;
}

 

 

* sprite기법 : 여러개의 이미지가 합쳐진 이미지 하나를 가져와서 필요한 부분만 노출시켜서 사용한다

네이버 홈페이지의 로고 예시