2012-01-27 45 views
3

有沒有辦法讓div在不知道div的寬度的情況下使用CSS僅出現在屏幕外一半?讓Div出現在屏幕外一半

+0

怎麼樣設置左側-50px或同樣 – jacktheripper 2012-01-27 19:12:58

+3

他怎麼能這樣做,如果他不知道有多寬? – j08691 2012-01-27 19:24:15

回答

5

除非我誤解了這個問題,我認爲這是可能與CSS,因爲我希望應該清楚從this jsfiddle

例HTML

<div class="container one"> 
    <div class="half">Hello there.</div> 
</div> 
    <div class="container two"> 
<div class="half">Hello there, you old dog.</div> 
    </div> 
<div class="container three"> 
    <div class="half">Hello there you old dog. Been up to your old tricks?</div> 
</div> 

的CSS

.container { 
    position: absolute; 
} 
.half { 
    position: relative; 
    right: 50%; 
} 
.two { 
    top: 30px; 
} 
.three { 
    top: 60px; 
} 
+0

不錯。沒想到那 – theliberalsurfer 2012-01-27 19:52:04

+0

正是我需要的,謝謝! – sgcharlie 2012-01-27 20:19:08

+0

不客氣。 – magicalex 2012-01-28 05:59:14

0

其實沒有。

div將其頂部定位在屏幕的50%處......您可以假定值會「排序」,如果您知道div或多或少的高度,它會看起來像是在中間預先。但總之,沒有。

僅限於使用表格或Javascript。

+0

你會如何使用表格?你可以使用'display:table'嗎? – mrtsherman 2012-01-27 18:58:18

+0

不,你會創建一個3行的表格(記住3行,3個圓柱?)......真的是舊式。不會推薦。 – Frankie 2012-01-27 18:59:31

+0

我猜你比我老弗蘭克=)。我不知道那個伎倆。 – mrtsherman 2012-01-27 19:00:33

0

我做了一些jQuery。希望它的後面 - http://jsfiddle.net/6Guc8/1/。它獲得元素寬度的一半,然後將它的一半吸出屏幕。

這裏是jQuery的

$(document).ready(function(){ 
    var half_width = $("div").width()/2; 
    $("div").css("left", -half_width); 
}); 

這裏是CSS

div{ 
    background: #555; 
    height: 100px; 
    width: 100px; 
    position: absolute; 
} 

下面是HTML

<!DOCTYPE html> 
<html> 

<head> 
    <script src="http://code.jquery.com/jquery-1.7.1.min.js" type="text/javascript">   </script> 
</head> 

<body> 
    <div> 
    </div> 
</body> 

</html> 
+0

感謝您的意見 – theliberalsurfer 2012-01-27 19:46:07

0

它是唯一的CSS絕對有可能的。您需要1個包裝的div,但是:

<!DOCTYPE html> 
<html> 

<head> 
    <style type="text/css"> 
     div#wrapper { 
      position: absolute; 
      left: 0; 
     } 
     div#wrapper div { 
      position: relative; 
      padding: 30px; 
      background: yellow; 
      left: -50%; 
     } 
    </style> 
</head> 

<body> 
    <div id="wrapper"> 
     <div>this div is halfway hidden, no matter what size it is.</div> 
    </div> 
</body> 

</html>