sgcharlie
sgcharlie

Reputation: 1036

Make a Div appear half off-screen

Is there a way to make a div appear half off-screen using just CSS without knowing the width of the div?

Upvotes: 5

Views: 10135

Answers (4)

magicalex
magicalex

Reputation: 937

Unless I've misunderstood the question, I think it is possible with CSS, as I hope should be clear from this jsfiddle.

Example 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>

The CSS

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

Upvotes: 6

Wes Pearce
Wes Pearce

Reputation: 259

It is absolutely possible in CSS only. You need 1 wrapper div, however:

<!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>

Upvotes: 0

mildog8
mildog8

Reputation: 2154

i made something from jQuery. Hope its what you are after - http://jsfiddle.net/6Guc8/1/. it gets half the width of the element and then chucks half of it out the screen.

here is the jquery

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

here is the css

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

here is the 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>

Upvotes: 0

Frankie
Frankie

Reputation: 25165

Actually, no.

The div will have it's top positioned at 50% the screen... you could assume values that would "sort of" make it look like it would be in the middle if you knew more or less the height of the div before-hand. But in short, no.

Only with tables or Javascript.

Upvotes: 0

Related Questions