How do I horizontally center a span element inside a div

I am trying to center the two links 'view website' and 'view project' inside the surrounding div. Can someone point out what I need to do to make this work?

JS Fiddle:

HTML

<div> <span> <a href="#" target="_blank">Visit website</a> <a href="#">View project</a> </span> </div> 

CSS

div { background:red;overflow:hidden } span a { background:#222; color:#fff; display:block; float:left; margin:10px 10px 0 0; padding:5px 10px } 
2

7 Answers

Another option would be to give the span display: table; and center it via margin: 0 auto;

span { display: table; margin: 0 auto; } 
4

One option is to give the <a> a display of inline-block and then apply text-align: center; on the containing block (remove the float as well):

div { background: red; overflow: hidden; text-align: center; } span a { background: #222; color: #fff; display: inline-block; /* float:left; remove */ margin: 10px 10px 0 0; padding: 5px 10px } 

3
<div> <span>Short text</span><br /> <span>This is long text</span> </div> 
0

Applying inline-block to the element that is to be centered and applying text-align:center to the parent block did the trick for me.

Works even on <span> tags.

Spans can get a bit tricky to deal with. if you set the width of teach span you can use

margin: 0 auto; 

to center them, but they then end up on different lines. I would suggest trying a different approach to your structure.

Here is the jsfiddle I cam e up with off the top of my head: jsFiddle

EDIT:

Adrift's answer is the easiest solution :)

only css div you can center content

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

I assume you want to center them on one line and not on two separate lines based on your fiddle. If that is the case, try the following css:

 div { background:red; overflow:hidden; } span { display:block; margin:0 auto; width:200px; } span a { padding:5px 10px; color:#fff; background:#222; } 

I removed the float since you want to center it, and then made the span surrounding the links centered by adding margin:0 auto to them. Finally, I added a static width to the span. This centers the links on one line within the red div.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like