2012-01-27 93 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>