2014-10-05 62 views
0

我有這樣的jsfiddle:Click here中心在div裏面的DIV自動

<div class="image-info"> 
     <img id="cart-image" src="http://www.wonderoftech.com/wp-content/uploads/2013/07/BlackBerry-Q10-Sample-3-300x300.jpg"> 
     <div class="pizza-hint">sample text</div> 
</div> 

所以在你上面的小提琴可以看到,當你懸停在DIV示範文本是不實際水平居中我試着保證金自動但它沒有工作。

我的問題是,如何在文本長度增加時自動居中?

+0

保證金汽車不會與崗位工作:絕對。你可能需要將你的工具提示包裝在一個額外的容器div中。 – stubailo 2014-10-05 06:22:20

回答

1

像這樣:

Demo

添加的東西:

.image-info { 
    position: relative; 
    display: inline-block; <-added 
    font-size: 0;   <-added 
} 

div:HOVER .pizza-hint { 
    display: block; 
    position: absolute; 
    top: 50%;         <- changed 
    left: 50%;         <- changed 
    border: 1px solid white;     
    -ms-transform: translate(-50%,-50%);  <- added 
    -webkit-transform: translate(-50%,-50%); <- added 
    transform: translate(-50%,-50%);   <- added 
    margin-left: 0;       <- changed 
    margin-right: 0;       <- changed 
    padding: 5px 5px 5px 5px; 
    border-radius: 5px; 
    background-color: rgba(227, 255, 255, 0.7); 
    background: rgba(227, 255, 255, 0.7); 
} 
1

一個跨瀏覽器的解決方案,

使用圖像爲image-info DIV的背景圖像。並使用下面的CSS,

HTML:

<div class="image-info" style="background-image:url(http://www.wonderoftech.com/wp-content/uploads/2013/07/BlackBerry-Q10-Sample-3-300x300.jpg);"> 
    <div class="pizza-hint">sample text</div> 
</div> 

CSS:

.image-info { 
    width:300px; 
    height:300px; 
    text-align: center; 
    background-color:blue; 
} 
.image-info:before { 
    content: ''; 
    display: inline-block; 
    height: 100%; 
    vertical-align: middle; 
    margin-right: -0.25em; 
} 

.pizza-hint { 
    font-size: 16px; 
    border: 1px solid white; 
    display: none; 
    vertical-align: middle; 
    border: 1px solid white; 
    padding: 5px 5px 5px 5px; 
    border-radius: 5px; 
    background-color: rgba(227, 255, 255, 0.7); 
    background: rgba(227, 255, 255, 0.7); 
} 

div:HOVER .pizza-hint { 
    display: inline-block; 
} 

HTML,CSS fiddle here