dagda1
dagda1

Reputation: 28910

position css arrow half way down div

I have a css arrow positioned at the size of my div.

Here is a jsbin that shows it in action.

How can I position the arrow half way down the div no matter what height the div is?

Upvotes: 4

Views: 7835

Answers (3)

Eamon Nerbonne
Eamon Nerbonne

Reputation: 48156

You don't actually need CSS3 for this; CSS2 suffices and without too much hackishness: http://jsbin.com/civijuvofo/1/edit?html,css,output - the essence is to do e.g. top: 50%; margin-top: -10px;.

In particular, you can position the white+gray triangles half-way down box with top: 50%;. Then they're too low - they start at the 50% midpoint, but they descend down to 50% + 2*borderwidth. You could use css3 calc to compensate, or a css3 transform, but the most compatible hack is simply to apply a negative top margin equal to the border width.

That means your "arrow" fan-out then looks as follows in CSS:

.container:before, .container:after {
    content: '';
    display: block;
    position: absolute;
    top: 50%;
    right: 100%;
    width: 0;
    height: 0;
    border-color: transparent;
    border-style: solid;
}

.container:before {
    margin-top:  -11px;
    border-width: 11px;  
    border-right-color: #dedede;
}

.container:after {
    margin-top:  -10px;
    border-width: 10px;
    border-right-color: #fff;
}

This 'll work cross-browser in pretty much any browser released in the past 10-15 years. I'm not sure about IE7 :-).

Upvotes: 2

Amr Noman
Amr Noman

Reputation: 2647

When you use position: absolute you can center things like this:

position: absolute;
top: 50%;
transform: translateY(-50%);

top: 50% assigns 50% of the parent's height to top

transform: translateY(-50%) moves the element up by 50% of the element's height.

This method works regardless of the element's height or the parent's height.

You can also use it to center things horizontally:

position: absolute;
left: 50%;
transform: translateX(-50%);

or both vertically and horizontally:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

http://jsbin.com/lixisidezu/1/edit?html,css,output

Upvotes: 7

wegelagerer
wegelagerer

Reputation: 3720

I'd do it by changing the way you calculate top, so in this case using "calc" and by subtracting border-width.

top: calc(50% - 10px)

Here is a working jsbin.

Upvotes: 3

Related Questions