How do I horizontally center a span element inside a div
CssCss Problem Overview
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
}
Css Solutions
Solution 1 - Css
Another option would be to give the span display: table;
and center it via margin: 0 auto;
span {
display: table;
margin: 0 auto;
}
Solution 2 - Css
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
}
Solution 3 - Css
<div style="text-align:center">
<span>Short text</span><br />
<span>This is long text</span>
</div>
Solution 4 - Css
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.
Solution 5 - Css
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 :)
Solution 6 - Css
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.
Solution 7 - Css
only css div you can center content
div{
display:table;
margin:0 auto;
}