[css] 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: http://jsfiddle.net/F6R9C/

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
}

This question is related to css

The answer is


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 :)


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.


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

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

<div style="text-align:center">
    <span>Short text</span><br />
    <span>This is long text</span>
</div>

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.


only css div you can center content

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

http://jsfiddle.net/4q2r69te/1/