ludwigschubert
ludwigschubert

Reputation: 662

Centering an image and text together, inside a button, both horizontal and vertical

I'm trying to build a button in pure CSS and fail spectacularly at aligning different elements. This is probably easy, but I can't get my head around it. Here's how it should look:

enter image description here

The button should contain both text and an image. Both should be vertically centered. Both of them together should be horizontally centered.

I can get either of this to work on its own, but not both at the same time.

I'm really looking for some guidance as to what would be the best way of doing this, but here's what I'm using so far, as simplified as possible for me:

<span style="display:table; text-align:center;">
<span style="display:table-cell; position:relative; ">
    <a href=… >
        <img style="position:absolute; top:50%; margin-top:-#{ height / 2}px"></img>
    </a>
</span>
    <a href=… > TEXT </a>
</span>

And this is the current result.

enter image description here

Note how the icon should be further to the right, and the text should be a little further to the right as well. My current understanding is that right now it's dead center because using absolute alignment for the icon removes it from the flow.

(Some of the strange variables due to me generating the HTML via ERB.)

Upvotes: 1

Views: 6254

Answers (2)

Reinstar
Reinstar

Reputation: 146

Did you search this HTML:

<html>
<head>
<style>
    .icon_button{
        background:#FFFFFF url(http://www.limitedlink.com/images/png/ico.png) no-repeat 4px 4px;
        padding:4px 4px 4px 22px;
        height:auto;
    }
</style>

</head>
<body>
    <input type="button" value="halo" class="icon_button" />
</body>
</html>

Upvotes: 0

Musa
Musa

Reputation: 97672

You could just use a button with some text an an image in it. Vertically align the contents of the button and add padding.

<button><span><img src="http://placehold.it/25x25">Some Text</span></button>​
button{
    padding: 1em 2em;
}
img, span{
    vertical-align:middle;
}

DEMO

Upvotes: 3

Related Questions