CSS

box-shadow를 이용하여 inner border처럼 보이게 하기

Lee92 2024. 12. 3. 12:45

 

width값과 height값이 정해지지 않은 아래와 같은 코드가 있다고 생각해보자.

 

    <div class="box-wrap">
        <div class="box box1">box1</div>
        <div class="box box2">box2</div>
        <div class="box box3">box3</div>
    </div>
        .box-wrap{
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 100px auto;
        }
        .box{
            padding: 5px 10px;
            margin-right: 5px;
            text-align: center;
            box-sizing: border-box;
        }
        .box1{
            background-color: #121212;
            color: #fff;
        }
        .box2{
            border: 1px solid #121212;
        }
        .box3{
            box-shadow: inset 0px 0px 0px 1px #121212;
        }

 

 

 

그러면 위와 같은 박스들이 생성되는데 box를 보면 border값 때문에 box1 크기에서 1px씩 더 밀려난 것을 확인할 수 있다. 

위의 코드를 보면 box-sizing을 통해 border-box; 속성을 넣어놨음에도 적용이 되지 않는 것을 볼 수 있는데 그것은 box-sizing의 속성값을 자세히 읽어보면 된다. 

 

The box-sizing CSS property sets how the total width and height of an element is calculated.

By default in the CSS box model, the width and height you assign to an element is applied only to the element's content box. If the element has any border or padding, this is then added to the width and height to arrive at the size of the box that's rendered on the screen. This means that when you set width and height, you have to adjust the value you give to allow for any border or padding that may be added. For example, if you have four boxes with width: 25%;, if any has left or right padding or a left or right border, they will not by default fit on one line within the constraints of the parent container.

출저 : https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing

 

box-sizingwidthheight값을 계산하는 속성을 설정한다.

더 자세히 설명하자면, CSS박스모델에서는 요소에 지정된 widthheight는 컨텐츠박스에만 적용이 되는데 만약 요소에 border와 padding이 있다면 이것들이 widthheight에 추가되어 화면에 렌더링 될 박스의 크기가 결정된다.

 

라고 설명을 하고 있다. 

즉, width값과 height값이 설정되어 있지 않은 박스에는 box-sizing: border-box;값을 넣어봤자 아무 의미가 없다. 

 

아까와 같은 박스들에 width: 500px; height: 100px; 값을 넣는다면 아래와 같이 box-sizing: border-box;가 잘 적용되는 것을 볼 수 있다. 

 

다시 정리하자면,

width, height값이 설정되어 있지 않다면 box-sizing은 적용되지 않는다.
box-sizing은 명시된 width, height값이 있어야지 적용이 된다. 

 

 

🙄 그렇지만, width값과 height값을 설정하지 않은 span과 같은 요소에 border값을 넣고 마치 box-sizing이 적용된 것처럼 만들고 싶다면 어떻게 해야할까? 

 

약간의 눈속임이지만 box-shadow 속성을 이용하는 방법이 있다. 

 

위의 코드에서 box3을 살펴보면 border와 다르게 box1과 같은 크기를 유지하고 있는데 이 속성을 위와 같이 설정하여 마치 innder border를 설정한 것처럼 보이게 할 수 있다. 

 

 

        .box3{
            box-shadow: inset 0px 0px 0px 1px #121212;
        }