2014-10-30 34 views
0

我想將一些文本放置在背景圖像的頂部,如下圖所示,文本應位於圖像右半部分的中心。任何人都知道如何解決此問題? enter image description here將文本放置在圖像右半部分的中心

HTML

<div class="full-width"> 
    <div class="text-center"><h2 class="text">text</h2></div>  
    <img src="img/example.jpg"> 

</div> 

CSS

.text{ 
    position:absolute; 
    margin-left: 50%; 
    margin-top: 1em; 


} 

.full-width{ 
    width:100%; 

} 

在評論中給出了一些解決方案,結果是這樣的:

enter image description here

+2

請分享現有的代碼,你就試了一下,到目前爲止...... – webeno 2014-10-30 08:01:21

+0

使用'的位置是:絕對的;頂部:50%;右:10%;' – 2014-10-30 08:02:44

+0

@GoosvandenBekerom我不會爲此擔心。你能否展示你的最佳解決方案?這樣我可以用我的解決方案來爭論。 – 2014-10-30 08:06:29

回答

-1

在我的意見,我只給一個想法沒有確切的解決方案。以下是您正在尋找的確切解決方案。

.full-width{position:relative; width:420px;} 
.text-center{position:absolute; top:50%; margin-top:-25px; right:25%; margin-right:-50px;} 
.text{padding:0; margin:0; width:100px; height:50px; border:1px solid #000;} 

FIDDLE DEMO

0

如果文本沒有DINAMIC,你可以隨時知道集裝箱會是什麼尺寸(beign容器中的inline-block的元素)。瀏覽器可能會顯示略有不同的文字,所以尺寸可能會改變一些像素。這意味着這個解決方案不會100%準確但接近。

,你可以在這個FIDDLE文字容器的尺寸是148×27(鉻)看,那麼你只需要調整頁邊距設置正確:

.text-center { 
    position:absolute; 
    left: 75%; 
    top: 50%; 
    margin-left:-74px; 
    margin-top:-27px; 
    display:inline-block;} 

.full-width{ 
    width:100%; 
    overflow:hidden; 
    position:relative; 

其中保證金左邊是的一半容器寬度。

希望這可以幫助你

編輯:或爲蘇雷什建議(更好的主意)設置一個固定的寬度文本中心與文本對齊:中心,並再次設置margin-左減一半像這樣更新的寬度FIDDLE

0

您可以通過文本元素和CSS變換的絕對定位來管理它。

通過我們的元件的左上角推到超過在div(如由圖像所定義的)的寬度的方式3/4元件top:50%, left:75%定位...

然後我們移動元件剩下一半是自己的,一半是它自己的高度,確保文本元素的中心現在剩下75%和50%下降/上升。這個是用`transform:translate(-50%, - 50%);

Full Page Jsfiddle Demo

注:我特意限制了文本元素爲超長文本可流出包裝DIV的寬度。

如果您知道文本不會溢出,也許是因爲您只有幾個字,則可以刪除max-width並設置white-space:nowrap;(當前註釋掉),文本將採用它自己的寬度。

* { 
 
    -webkit-box-sizing: border-box; 
 
    -moz-box-sizing: border-box; 
 
    box-sizing: border-box; 
 
} 
 

 
.full-width { 
 
    position: relative; 
 
    display: inline-block; 
 
} 
 

 
.text-center { 
 
    background: rgba(255,255,255,0.25); 
 
    color:white; 
 
    position: absolute; 
 
    left:75%; 
 
    top:50%; 
 
    border:1px solid black; 
 
    width:auto; 
 
    text-align: center; 
 
    max-width:25%; /* see note */ 
 
    /*white-space:nowrap; */ 
 
    transform:translate(-50%,-50%); 
 
}
<div class="full-width"> 
 
    <div class="text-center"> 
 
     <h2 class="text">Lorem ipsum dolor.</h2> 
 
    </div> 
 
    <img src="http://lorempixel.com/output/animals-q-c-640-250-4.jpg"/> 
 
</div> 
 

 
<div class="full-width"> 
 
    <div class="text-center"> 
 
     <h2 class="text">Lorem ipsum dolor sit amet, consectetur.</h2> 
 
    </div> 
 
    <img src="http://lorempixel.com/output/nightlife-q-c-800-300-7.jpg"/> 
 
</div>

相關問題