nbg15 nbg15 - 17 days ago 7
CSS Question

How to center a span in a div

i have already tried many thing to center a span Element (which contains couple of DIVs) in a wrapper DIV (in this case the soccerField DIV)...

HTML structure looks like this:

<div id="soccerField">
<span id="defendLine">
<div>player 1</div>
<div>player 2</div>
<div>player 3</div>
<div>player 4</div>
</span>
<div>


CSS looks like this:

#field{
padding: 0%;
min-width: 250px;
min-height: 1000px;
max-width: 800px;
position: relative;
text-align: center
}

#defendLine{
display: inline-block;
}


at the moment it looks like:
enter image description here

at the end it should looks like:
enter image description here

but this result i only get when I am using this code:

#defendLine{
position: absolute;
left:59px
}


but this is not the right way I think becasue when I have only 3 players or 5 players at my DefendLine, i also have to give some "left: X" values. But i want to make it dynamically. >> doesnt matter how much players, always center the span element, independentley how much players my includes.

I have already check these articles which helps other, but in this case. I couldnt help myself :(

CSS How to center a div horizontally
How do you easily horizontally center a <div> using CSS?

I would be really happy if anyone could give me a hint!

Edit:

I have created a fiddle, i tried all solutions out. I think something else is the reason for my problem :(

https://jsfiddle.net/rztad75y/2/

Answer

using a <span> tag is a bad practice. instead, change it to a <div> like this:

HTML

<div id="soccerField">
    <div id="defendLine">
        <div>player 1</div>
        <div>player 2</div>
        <div>player 3</div>
        <div>player 4</div>
    </div>
<div>

CSS

#defendLine{
 width: 90%;
 margin: 0 auto;  
}

Edit if you'd like to center the content of the div itself, set text-align:center or simply use flexbox:

display:flex;
justify-content: center;
align-items: center;

more info could be found here: https://css-tricks.com/snippets/css/a-guide-to-flexbox/