Acidic
Acidic

Reputation: 6280

Mouse events and block elements

In my documents I have a few divs with text-align: center:

<div>bla bla</div>
<div>bla bla bla bla</div>
<div>bla bla bla</div>

The problem is that while the content inside might not be large, the width: 100% of the divs potentially makes them a lot wider than the content. Mouse events are caught in all of the illustrated area: enter image description here

I created my own custom tooltip in JavaScript, and having it appear when the mouse is so far off left or right from the content simply doesn't look right.

Instead, I would like for the tooltip to appear only when it hovers over the contents of the div, or at least make it look that way: enter image description here

Setting the display of the divs to inline-block does size them down to the width of the content, but it also makes all the div appear in the same line.
Is there any way to achieve what I want without using display: inline and inserting <br>s between all the divs? This simply doesn't look like a convenient solution.

Edit: As suggested in the comments, another possible solution is to wrap the content of each div in a span element and add the mouse event to that, but that doesn't sound like a convenient solution either, especially since the content of the divs might be changed programmatically.

Upvotes: 3

Views: 109

Answers (2)

johnsoe
johnsoe

Reputation: 674

Setting the display type to table while also setting the margin to 0 auto will accomplish what you need.

div {
    display: table;
    margin: 0 auto;
}

You also don't need text-align: center anymore for this to work. http://jsfiddle.net/NEqvD/

Upvotes: 2

DRD
DRD

Reputation: 5813

Here's a solution using floating: http://jsfiddle.net/3KH5k/1/. Floats like absolute blocks, inlines, and inline-blocks shrinkwrap their content.

HTML:

<div>bla bla</div>
<div>bla bla bla bla</div>
<div>bla bla bla</div>

CSS:

div {
    outline: 1px solid red;
    float: left;
    clear: left;
    position: relative;
    left: 50%;
    -webkit-transform: translateX(-50%);
    transform: translateX(-50%);
    margin-bottom: 10px;
}

Upvotes: 1

Related Questions