CSS에서 이미지 위에 텍스트를 배치하는 방법


123

CSS에서 이미지 위에 텍스트를 중앙에 배치하려면 어떻게합니까?

<div class="image">
    <img src="sample.png"/>
    <div class="text">
       <h2>Some text</h2>
    </div>
</div>

아래와 같이하고 싶은데 어려움이 있습니다. 현재 CSS입니다.

<style>
.image {
   position: relative;
}

h2 {
   position: absolute;
   top: 200px;
   left: 0;
   width: 100%;
   margin: 0 auto;
   width: 300px;
   height: 50px;
}
</style>

여기에 이미지 설명 입력

배경 이미지를 사용할 때 html2pdf에서 출력을 얻지 못합니다.

<style>
#image_container{
    width: 1000px;
    height: 700px;
    background-image:url('switch.png');
}
</style>
<a href="prints.php">Print</a>
<?php ob_start(); ?>
<div id="image_container"></div>
<?php 
$_SESSION['sess'] = ob_get_contents(); 
ob_flush();
?>

다음은 prints.php입니다.

<?php require_once('html2pdf/html2pdf.class.php'); ?>
<?php
$html2pdf = new HTML2PDF('L', 'A4', 'en');
$html2pdf->writeHTML($_SESSION['sess']);
$html2pdf->Output('random.pdf');
?>

배경 이미지로 만들 수 있습니까?
Webwoman

답변:


174

다음과 같은 것은 어떻습니까? http://jsfiddle.net/EgLKV/3/

position:absolute및 사용 z-index하여 이미지 위에 텍스트를 배치합니다.

#container {
  height: 400px;
  width: 400px;
  position: relative;
}
#image {
  position: absolute;
  left: 0;
  top: 0;
}
#text {
  z-index: 100;
  position: absolute;
  color: white;
  font-size: 24px;
  font-weight: bold;
  left: 150px;
  top: 350px;
}
<div id="container">
  <img id="image" src="http://www.noao.edu/image_gallery/images/d4/androa.jpg" />
  <p id="text">
    Hello World!
  </p>
</div>


14
당신은 Z- 인덱스 피할 수
FOOBAR

8
@danielad : 답변을 편집 할 때까지 잘 작동했습니다. 편집 내용을 롤백했습니다.
xbonez

haah--가 나 한테 감사 난 그냥 --it 어제 작동하지 않는까지 수정 일에 당신을 생각 나게 - 헬로우 세계 텍스트 vene
다니엘 Adenew

이미지 중간에 텍스트를 어떻게 가져올 수 있습니까? 왼쪽 200, 아래쪽 200?
메이슨 H. 하트 필드

4
슬프게도 컨테이너의 크기를 수정할 때 사이트가 현대적이고 반응이 빠른 관행을 따르기를 원한다면 정말 나쁜 옵션이됩니다 (답변은 2012 년부터 였으므로 이해할 수 없을 정도로 오래되었습니다). 훨씬 더 나은 솔루션은 다음에서 찾을 수 있습니다. stackoverflow.com/questions/43333495/text-over-image-responsive
Sk446

30

이것은 반응 형 크기로 작업하는 또 다른 방법입니다. 텍스트를 중앙에 유지하고 부모 내에서 위치를 유지합니다. 중앙에 배치하지 않으려면 absolute매개 변수로 작업하는 것이 더 쉽습니다 . 기본 컨테이너는 display: inline-block. 작업중인 작업에 따라이를 수행하는 다른 방법이 많이 있습니다.

미지중심에 기반

여기에서 작동하는 코드 펜 예제

HTML

<div class="containerBox">
    <div class="text-box">
        <h4>Your Text is responsive and centered</h4>
    </div>
    <img class="img-responsive" src="http://placehold.it/900x100"/>
</div>

CSS

.containerBox {
    position: relative;
    display: inline-block;
}
.text-box {
    position: absolute;    
    height: 100%;
    text-align: center;    
    width: 100%;
}
.text-box:before {
   content: '';
   display: inline-block;
   height: 100%;
   vertical-align: middle;
}
h4 {
   display: inline-block;
   font-size: 20px; /*or whatever you want*/
   color: #FFF;   
}
img {
  display: block;
  max-width: 100%;
  height: auto;
}

6
이 솔루션은 설정된 높이 또는 너비를 지정할 수없는 경우에 적합합니다.
Yazmin

8

또는 CSS 클래스 sample.png의 배경 이미지로 설정하지 않는 이유는 무엇 입니까? 이것은 이미지 위에 쓴 것처럼 효과를 줄 것입니다.texth2


2
이미지가 문서의 의미 론적 부분이어야한다면 어떻게해야합니까?
animuson

@animuson : 나는 이것이 여기의 경우라고 생각하지 않습니다. : \
Harry Joy

html2pdf를 사용하여 PDF를 생성하고 배경 이미지를 사용하면 아무것도 얻지 못합니다.
Wern Ancheta 2012 년

8
@KyokaSuigetsu : html2pdf를 사용하고 있음을 포함하도록 질문 제목을 변경해야합니다.
Harry Joy

6

반응 형 디자인의 경우 상대적인 레이아웃과 고정 된 레이아웃을 가진 콘텐츠 (컨테이너에 배치)를 가진 컨테이너를 사용하는 것이 좋습니다.

CSS 스타일 :

/*Centering element in a base container*/

.contianer-relative{ 
  position: relative;
 }

.content-center-text-absolute{ 
  position: absolute; 
  text-align: center;
  width: 100%;
  height: 0%;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 51;
}

HTML 코드 :

<!-- Have used ionic classes -->
<div class="row">
    <div class="col remove-padding contianer-relative"><!-- container with position relative -->
        <div class="item item-image clear-border" ><a href="#"><img ng-src="img/engg-manl.png" alt="ENGINEERING MANUAL" title="ENGINEERING MANUAL" ></a></div> <!-- Image intended to work as a background -->
        <h4 class="content-center-text-absolute white-text"><strong>ENGINEERING <br> MANUALS</strong></h4><!-- content div with position fixed -->
    </div>
    <div class="col remove-padding contianer-relative"><!-- container with position relative -->
        <div class="item item-image clear-border"><a href="#"><img ng-src="img/contract-directory.png" alt="CONTRACTOR DIRECTORY" title="CONTRACTOR DIRECTORY"></a></div><!-- Image intended to work as a background -->
        <h4 class="content-center-text-absolute white-text"><strong>CONTRACTOR <br> DIRECTORY</strong></h4><!-- content div with position fixed -->
    </div>       
</div>

IONIC 그리드 레이아웃, 균등 한 간격의 그리드 요소 및 위 HTML에서 사용 된 클래스에 대해서는- 그리드 : 균등 한 간격의 열을 참조하십시오 . 도움이 되었기를 바랍니다 ... :)


4

Harry Joy가 지적했듯이 이미지를 div의 배경으로 설정 한 다음 한 줄의 텍스트 만있는 경우 텍스트의 줄 높이를 div 높이와 동일하게 설정할 수 있습니다. 그러면 텍스트가 div의 중심.

라인이 두 개 이상인 경우 디스플레이를 테이블 셀로 설정하고 세로 정렬을 가운데로 설정해야합니다.


html2pdf를 사용하여 pdf를 만듭니다. 배경 이미지를 사용하면 이미지가 보이지 않습니다. 내 편집을 참조하십시오.
Wern Ancheta 2012 년

죄송합니다. html2pdf가 뭔지 모르겠습니다.
Yevgeny Simkin 2012 년

1

2017 년부터는 반응이 더 빠르고 저를 위해 일했습니다. 배지처럼 텍스트를 안쪽과 위에 넣는 것입니다. 숫자 8 대신 데이터베이스에서 데이터를 가져 오는 변수가있었습니다.

이 코드는 위의 Kailas 답변으로 시작되었습니다.

https://jsfiddle.net/jim54729/memmu2wb/3/

내 HTML

<div class="containerBox">
  <img class="img-responsive"    src="https://s20.postimg.org/huun8e6fh/Gold_Ring.png">
  <div class='text-box'>
   <p class='dataNumber'> 8 </p>
  </div>
</div>

그리고 내 CSS :

.containerBox {
  position: relative;
  display: inline-block;
}

.text-box {
  position: absolute;
  height: 30%;
  text-align: center;
  width: 100%;
  margin: auto;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  font-size: 30px;
}

.img-responsive {
  display: block;
  max-width: 100%;
  height: 120px;
  margin: auto;
  padding: auto;
}

.dataNumber {
  margin-top: auto;
}

-1

똑같이하는 작고 짧은 방법

HTML

<div class="image">
     <p>
        <h3>Heading 3</h3>
        <h5>Heading 5</h5>
     </p>
</div>

CSS

.image {
        position: relative;
        margin-bottom: 20px;
        width: 100%;
        height: 300px;
        color: white;
        background: url('../../Images/myImg.jpg') no-repeat;
        background-size: 250px 250px;
    }
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.