Reputation: 1516
on facebook if you hover over something with a lot of likes a div pops up showing everyone who likes the post. i was wondering if anyone could mimic the div in css and explain how i can do it. there is a picture below showing what i mean. i know you have to use a :after in css but im not sure how to position the triangle and all that.
Here is some code i found somewhere else:
#pointed {
position: relative;
margin: 0 auto;
width: 200px;
height: 200px;
background-color: white;
}
#pointed:after,
#pointed::after {
position: absolute;
top: 100%;
left: 50%;
margin-left: -50%;
content: '';
width: 0;
height: 0;
border-top: solid 150px red;
border-left: solid 100px transparent;
border-right: solid 100px transparent;
}
Upvotes: 1
Views: 456
Reputation: 12869
The code you pasted there has the gist of it down. You can see a working JSFiddle here that makes it more like what you're going for.
There are two parts to this problem, I think. The first part is making the triangle. The second part is positioning the triangle.
The borders on the pseudoelement are responsible for that triangle we're seeing. If you're not sure how that's happening, take a look at this great answer that explains it quite well, I think.
The key to positioning involves making the child appear outside of the parent. We can do this by setting absolute
positioning on the child. However, if we do this without changing the parent at all, the absolute
positioning will be set relative to the window.
What we want here is positioning the child relative to the parent. We can do this by setting the parent element's positioning to anything other than static
, which is the default value. In the code you pasted, you can see they set it to relative
. For more about positioning, the working docs are pretty explanatory, I think. Another great resource can be found on CSS Tricks.
Anyway, we want our child to be just outside the parent. Accordingly, if we have a 5px high triangle, the child's CSS for positioning should look something like:
position: absolute;
top: -5px;
This will make it appear like its attached to the top, as you can see in the above JSFiddle.
After you've positioned it vertically the way you want it to, set its left
positioning to get it where you want along the horizontal.
Though of course you must ask yourself if it's worth reinventing the wheel—tooltips come with Bootstrap Jquery.
Upvotes: 3