2016-02-23 19 views
1

這是一個棘手的,如果它太棘手,我想圖像可以保持相同的大小。如何將文本置於流暢變化的圖像上(flexbox)?

我想將文本置於圖像頂部的中間,就像它是背景一樣,但我不想使用實際的背景。

我也想保留我當前的flexbox的行爲,因爲我喜歡它。這意味着:

  • 每行三項。
  • 圖像寬度爲66px。
  • 調整小瀏覽器寬度的圖像(不是非常需要)。
  • 沒有硬編碼行,它應該自動溢出到新行。

HTML:

<div class="container"> 
    <div class="circle box"> 
    <img src="http://i.imgur.com/4JtXH2S.png"> 
    <div class="circle text"> 
     70 
    </div> 
    </div> 
    <div class="circle box"> 
    <img src="http://i.imgur.com/4JtXH2S.png"> 
    <div class="circle text"> 
     70 
    </div> 
    </div> 
    <div class="circle box"> 
    <img src="http://i.imgur.com/4JtXH2S.png"> 
    <div class="circle text"> 
     70 
    </div> 
    </div> 
    <div class="circle box"> 
    <img src="http://i.imgur.com/4JtXH2S.png"> 
    <div class="circle text"> 
     70 
    </div> 
    </div> 
    <div class="circle box"> 
    <img src="http://i.imgur.com/4JtXH2S.png"> 
    <div class="circle text"> 
     70 
    </div> 
    </div> 
    <div class="circle box"> 
    <img src="http://i.imgur.com/4JtXH2S.png"> 
    <div class="circle text"> 
     70 
    </div> 
    </div> 
</div> 

CSS:

.container { 
    display: -webkit-flex; 
    display: flex; 
    align-items: center; 
    justify-content: center; 
    max-width: 100%; 
    height: auto; 
    flex-wrap: wrap; 
} 

.container .circle.box { 
    width: 33.33%; 
    width: calc(100%/3); 
    height: auto; 
} 

.circle.box img { 
    width: 100%; 
    max-width: 66px; 
} 

.circle.box .text { 
    font-size: 30px; 
} 

的jsfiddle:https://jsfiddle.net/hceac6mx/

還應當指出的是,我使用的是簡單的圓形,而在這裏,可以是CSS '編,這只是一個例子。所以對實際圖像的需求是真實的。

這是如何實現的?

回答

2

下面是可爲你工作(或至少是朝着正確方向邁出的一步,希望)一種方法:

  • 使每個DIV保持圖像和文本爲絕對定位的包含塊。

    .container .circle.box { position: relative; } 
    
  • 使用絕對定位將文本居中在圖像上。

    .circle.box .text { 
        position: absolute; 
        top: 0; 
        left: 0; 
        transform: translate(50%, 50%); 
    } 
    

Revised Fiddle

文字居中的圖像時,是非常小的不破,但我張貼了這個答案,因爲你提到圖像尺寸調整不是絕對必要的。


UPDATE

在評論,Gerrit Bertier已經發布了一個enhanced demo使文字響應,也是如此。

+1

我更新了一下你的解決方案,允許文本重新調整時,重新調整圓圈:https://jsfiddle.net/hceac6mx/2/在文本中添加了一個'width'和'max-width',設置了'左'到'0'和'文本對齊'到'中心' –

+0

@GerritBertier,很好地完成!謝謝。 –

+0

謝謝你們。任何想法如果我想要圖像的一排居中,該怎麼辦?使用'margin'和'text-align'會弄亂絕對定位。爲什麼不對齊項目:中心工作? – Yeats