Andreas
Andreas

Reputation: 2397

Place icon next to centered element on hover without centering the icon

I'm trying to add an icon next to a centered text on hover, wo centering both text and icon. I want the icon to be placed directly after the centered element. Picture should explain it. Preferably I would like to use flexbox. This is what i currently have: http://jsfiddle.net/TmdZ3/

HTML

<div class="container">
    <span>Label</span>
    <i>icon</i>
</div>

CSS

.container {
    height: 150px;
    width: 150px;
    border: 5px solid grey;
    display: flex;
    align-items: center;
    justify-content: center;
}

i {
    display: none;
}

.container:hover > i {
    display: flex;
}

enter image description here

Upvotes: 1

Views: 633

Answers (3)

Seimen
Seimen

Reputation: 7250

You'll have to make a small change to your markup and put the icon inside the span to then position it relative to its parent:

http://jsfiddle.net/TmdZ3/1/

span {
    position: relative;
}

i {
    display: none;
    position: absolute;
    top: 0;
    right: -30px;
}

Note that the right: -30px; would have to be adjusted according to your icon's size and spacing to the span.

Upvotes: 1

SW4
SW4

Reputation: 71160

What have you tried at present? Have a look at this FIDDLE which expands on the code example below.

This should be done by setting the background of the :hover css to something like:

background-image:url(myicon.png);
background-repeat:no-repeat;
background-position:right center;

The the regular link css to something like

padding:0 15px;

Upvotes: 0

Nitesh
Nitesh

Reputation: 15749

You should create a new span, make its position to be absolute, keeping relative to its immediate parent and then he would get what he is looking for on hover.

WORKING DEMO

The Code:

<div class='wrapper'>
    <span>Label</span>
</div>

.wrapper{
    padding:20px;
    border:4px solid grey;
    display:inline-block;
    color:black;
    font-size:22px;
    font-family:verdana;  
    position:relative;
     width:100px;
    height:30px;
}

span{
    padding:0 20px;
    color:black;
    text-decoration:none;
    position:absolute;

}

Hope this helps.

Upvotes: 0

Related Questions