[css] Layout (box-sizing, margin-collapsing, position)

JINN·2023년 6월 18일
1

box-sizing

width를 사용하여 content크기를 동일하게 결정하더라도 border값이 다르기때문에 크기가 다름.
이런경우 box-sizing: border-box를 사용하면
border가 적용된 것을 기준으로 box크기를 정할 수 있다.

<style>
        div{
            margin: 10px;
            width: 150px;
            box-sizing: border-box;
        }
        #small{
            border: 10px solid black;  
        }
        #large{
            border: 30px solid black;
        }
    </style>
</head>
<body>
    <div id="small">Hello</div>
    <div id="large">Hello</div>

margin-collapsing (마진겹침)

두 속성의 겹치는 마진값중 큰 마진값으로 서로의 간격이 정해진다.
만약 리스트에서 마진겹침이 없다면 두배로 간격이 벌어질 수 있기때문에 보기 안좋을 수 있다.

부모 요소, 자식 요소의 마진 값 중 큰 마진값이 자식 요소의 마진 값으로 사용된다.
(부모 요소가 투명할 경우)

position

-relative VS static

포지션 타입을 지정해 위치와 관련된 설정을 할 수 있다.

position relative: 부모에 대해 상대적으로 위치 이동
position static: 원래 위치해야 하는곳에 정적으로 위치

포지션 타입이 reltaive여야 그때 offset을 사용할 수 있다.

-absolute (절대포지션)

position absolute: 절대적 위치 지정 (html을 기준으로)
absolute를 사용하면 부모-자식 관계 또한 끊기게됨. 즉 크기 지정값 또한 끊기게 되므로
따로 지정해줘야함

absolute의 경우 static이 아닌 부모가 나타날때서야 그것을 기준으로 위치를 지정함.
즉 아래의 경우 parent가 아닌 grand를 기준으로 me의 기준이 정해진 것이다.

   <style>
        #parent, #other,#grand{
            border: 5px solid tomato;
            }
            #grand{
                position: relative;
            }
        #me{
            background-color: black;
            color: white;
            position: absolute;
            width:20px;
            left: 0;
            top: 0;
        }    
    </style>
</head>
<body>
    <div id="other">other</div>
    <div id="grand">
        grand
    <div id="parent">
        parent
        <div id="me">me
    </div>
</body>
</html>

-fixed

스크롤이 생긴 경우, absolute의 경우 스크롤을 내리면 사라지지만,
fixed를 사용할 경우 스크롤을 내려도 그 위치에 고정되어 있음을 확인할 수 있다.

position: fixed;

하단에 고정된 UI 형태를 만들고 싶은 경우에도 활용할 수 있다.

 #me{
            background-color: black;
            color: white;
            position:fixed;
            left: 0;
            bottom: 0;
            text-align: center;
            width: 100%;
        }    
    </style>

스크롤의 위치와 관계없이 화면 하단에 고정된 형태가 가능하다.

profile
가보자고?

0개의 댓글