2014-02-15 103 views
0

我似乎無法獲得像在頭垂直對齊。據水平對齊,但它是有點過頭了對頭部的頂部。對準圖像垂直居中

的HTML:

<!DOCTYPE html> 
<html> 
<head> 
<link rel="stylesheet" type="text/css" href="home_style.css"> 
</head> 

<body> 

<div class="header"> 
    <div class="search_bar"> 
    <input type="text" name="search" placeholder="Search magical instruments, tricks, books and more"> 
</div> 
<div class="user_settings"> 
    <img src="onebit_09.png" width="48px" height="48px"> 
</div> 

</body> 
</html> 

的CSS:

html,body{ 
height:100%; 
min-height:100%; 
width:100% 
min-width:100%; 
} 

.header{ 

margin-top:0; 
margin-bottom:0; 
height:10%; 
width:100%; 
background-color:#343430; 



} 

.search_bar input[type="text"]{ 
position:absolute; 
left:20%; 
top:4%; 
width:27%; 
padding:5px; 
padding-right:50px; 
outline:none; 
border: 2px solid #9C4B8F; 
border-radius: 5px; 
background-color:#FBFBFB; 
font-family: Cambria, Cochin, Georgia, serif; 
font-size: 16px; 
color:grey; 
background-image: url('search.png'); 
background-position: 100% -10px; 
background-repeat:no-repeat; 

} 

.search_bar input[type="text"]:focus{ 
background-color:#FFFFFF; 
border-color:#333333; 

} 
.user_settings img 
{ 
position:absolute; 
top:5%; 
left:95%; 
height:48px; 
width:48px; 
margin:-24px 0 0 -24px; 


} 

,我試圖給位置的圖像是一個小設置COG(user_settings)即48px寬和48px高。

+6

W3C已經長和詳盡的諮詢過程後確定與自己在浴室鏡子的元素的垂直居中/立場是,沒有一個心智正常的人會可能是有史以來想要的東西......他們建議傾斜你的頭向右或90度左,使用「水平」爲中心來代替。 –

回答

0

我解決了這個問題,我忘記了將html,body元素的填充和邊距設置爲0.這在屏幕頂部造成了一個小的白色間隙,使得它看起來像圖像不是定位正確。很抱歉給您帶來不便更正後的代碼應該是這樣的:

html,body{ 
height:100%; 
min-height:100%; 
width:100% 
min-width:100%; 
margin:0; 
padding:0; 
} 
0

嘗試使用計算值,它不會在所有瀏覽器中工作,但在有些人會做的事:

.user_settings img 
{ 
position:absolute; 
top:5%; 
left:95%; 
height:48px; 
width:48px; 
margin-top: calc(50% - 24px); 
margin-top: -webkit-calc(50% - 24px); 
margin-top: -moz-calc(50% - 24px); 
} 

,或者你可以試試自動保證金:

.user_settings img 
{ 
position:absolute; 
top:0; 
bottom:0; 
left:95%; 
height:48px; 
width:48px; 
margin-top: auto; 
} 

還是我最喜歡和最可靠的是使用一些javascript操縱位置。

例如jQuery的是這樣的:

$(".user_settings img").css('top',$(".user_settings).height()/2-24); 

然後確保你還可以添加一個調整大小觀察家這樣的:

$(window).on('resize', function(){ 
$(".user_settings img").css('top',$(".user_settings).height()/2-24); 
}); 
2

這裏是一個解決辦法:

#elementToAlignVertically 
{ 
margin-top:50%; 
transform:translate(0px,-50%); 
-ms-transform:translate(0px,-50%); 
-moz-transform:translate(0px,-50%); 
-webkit-transform:translate(0px,-50%); 
} 

Basicaly你從頂部對齊元件50%,然後用翻譯來移動它的-50%,這是HIGHT所以它會分呃它自己。

也許你還必須設置元素的高度,它要向上移動元素%使用像素的工作或代替。

0

在不久的將來(現在有喜歡的瀏覽器支持的70%),你可以做到這一點,一個更簡單和優雅的解決方案:

.container img{ 
    width: 100%; 
    height: auto; 
} 
@supports(object-fit: cover){ 
    .container img{ 
     height: 100%; 
     object-fit: cover; 
     object-position: center center; 
    } 
}