본문 바로가기
CSS

[CSS] inline-block의 문제점과 해결방법 (태그사이의 공백과 baseline)

by 메이플 🍁 2022. 4. 24.

inline-block의 특징

  • 베이스는 inline 요소지만 block 요소의 몇가지 특징을 가지고 있는 요소
  • 요소가 수평으로 쌓인다 (inline의 특성)
  • 태그 사이에 공백이 있으면 (요소 사이에 스페이스, 요소 사이에 한줄 띄우기) 화면에 공백이 나타난다 (inline의 특성)
  • width와 height를 가질수 있다 (block의 특성)
  • margin, padding으로 사방에 공백을 만들 수 있다 (block의 특성)

 

inline-block으로 레이아웃을 만들때 문제점 2가지

1. 태그 사이에 공백이 있으면 요소에 공백이 나타난다

1) 태그 사이에 공백이 없을때 요소 사이에 공백이 나타나지 않는다

<div class="left">Left</div><div class="right">Right</div>
div {
  width: 100px;
  height: 300px;
  color: white;
  display: inline-block;
}

.left {
  background-color: orange;
}

.right {
  background-color: royalblue;
}

2) 태그 사이에 공백이 있을때 요소 사이에 공백이 나타난다

<div class="left">Left</div> <div class="right">Right</div>
div {
  width: 100px;
  height: 300px;
  color: white;
  display: inline-block;
}

.left {
  background-color: orange;
}

.right {
  background-color: royalblue;
}

3) 태그 사이를 한줄 띄었을때 요소 사이에 공백이 나타난다

<div class="left">Left</div>
<div class="right">Right</div>
div {
  width: 100px;
  height: 300px;
  color: white;
  display: inline-block;
}

.left {
  background-color: orange;
}

.right {
  background-color: royalblue;
}

 

공백 해결방법

1) 빈 공간 주석 처리하기

<div class="left">Left</div><!--  --><div class="right">Right</div>

2) 닫는 태그를 다음 줄로 밀어내기

<div class="left">Left</div
><div class="right">Right</div>

3) 부모 요소의 글자 크기를 0으로 설정

<div class="container" style="font-size: 0">
  <div class="left">Left</div>
  <div class="right">Right</div>
</div>
.left, .right {
  width: 100px;
  height: 300px;
  color: white;
  font-size: 40px;
  display: inline-block;
}

.left {
  background-color: orange;
}

.right {
  background-color: royalblue;
}

 

2. baseline 위에 요소가 위치한다

이미지에 있는 빨간선을 베이스라인이라고 한다

<div class="left"></div>
<div class="right">Right</div>
.left, .right {
  width: 100px;
  height: 300px;
  color: white;
  display: inline-block;
}

.left {
  background-color: orange;
}

.right {
  background-color: royalblue;
}

baseline 해결방법

vertical-align: top을 설정해준다

.left, .right {
  width: 100px;
  height: 300px;
  color: white;
  font-size: 40px;
  display: inline-block;
}

.left {
  background-color: orange;
}

.right {
  background-color: royalblue;
  vertical-align: top;
}

댓글