Developer's blog

[CSS] 이미지 가운데 텍스트 띄우기 본문

FrontEnd/CSS

[CSS] 이미지 가운데 텍스트 띄우기

DevNoah 2022. 5. 10. 23:06

오늘은 이미지 위에 텍스트를 올려 원하는 위치에 배치하는 기능을 개발하고자 하였다.

 

개발할 때의 이슈는 나는 이미지에 position: relative;를 적용시켜 개발하고자 하였다. 하지만 이미지에 해당 css를 적용시키니 기능하지 않았다.

 

그 이후로 여러 시행착오를 겪은 결과로 원하는 결과를 이끌어내기 위해서는

이미지와 오버레이 시키고자 하였던 텍스트를 하나의 div로 묶고 해당 div에 position: relative; 주며 이미지는 width: 100%;  vertical-align: middle; 를 통해 꽉채우고 텍스트에 position: absolute; 를 적용시켜 개발해야한다는 것을 알게되었다.

아래는 개발된 html 코드이다.

<div class="col-lg-6 px-5 text-center img-wrap">
	<div class="img-wrap-text-1">
		<div class="fs-2 ff-nb mb-4 fst-normal text-center">{ 어린이 생활 과학 교실 }</div>
	</div>
	<div class="img-wrap-text-2">
		<div class="fs-4 ff-nr fst-normal text-center">수료증</div>
	</div>
	<div class="img-wrap-text-3">
		<div class="fs-2 ff-nb mb-4 fst-normal text-center">홍길동</div>
	</div>
	<div class="img-wrap-div">
		<img class="" src="https://dummyimage.com/480x600/FFFFFD/6c757d" alt="...">
	</div>
	<img class="img-fluid rounded mb-5 mb-lg-0" src="/images/create_background.png" alt="create_background" style="width: 800px; height: 1010px">
</div>

아래는 개발된 css 코드이다.

.img-wrap {
  position: relative;
}

.img-wrap img {
  width: 100%;
  vertical-align: middle;
}

.img-wrap-text-1 {
  text-align: center;
  position: absolute;
  top: 10%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.img-wrap-text-2 {
  text-align: center;
  position: absolute;
  top: 15%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.img-wrap-text-3 {
  text-align: center;
  position: absolute;
  top: 20%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.img-wrap-div {
  text-align: center;
  position: absolute;
  top: 61%;
  left: 50%;
  transform: translate(-50%, -50%);
}

 

참고사이트

https://codepen.io/LiveBlogger/pen/YzWqdJQ