J. Doe J. Doe - 4 months ago 7
HTML Question

Horizontally centering div and span with input child

I need this input field to prepend a # before the hex colour code, like so, as well as horizontally center both the div and the span containers:

<div id="color_wrapper">
<span>#<input type="text" value="ffffff"></span>
</div>


When I try with the following css:

html, body{
margin:0;
padding:0;
font-size:22px;
color:#fff
}

#color_wrapper{
border: none;
background-color:#444;
text-align:center;
}

span, input {
border: none;
}

input{
outline:none;
width:85px;
background-color:transparent;
font-size:inherit;
color:inherit;
display:inherit;
}


I achieve limited success, in that the hash is at the start and the span and input seem to be centered. The problem occurs when I attempt to set the width of the div, and though the width is set, it snaps back to the left.

So, how can I center the div and the span, while also being able to change the div's width?

Here's a fiddle with the code.

Answer

Just specify margin: 0 auto for your div.

html body{
	margin:0;
	padding:0;
	font-size:22px;
	color:#fff
}

#color_wrapper{
  width:300px;
	border: none;
	background-color:#444444;
	text-align:center;
  margin:0 auto;
}
 
span, input {
    border: none;
}

input{
	outline:none;
	width:85px;
	background-color:transparent;
	font-size:inherit;
	color:inherit;
	display:inherit;
}
<div id="color_wrapper">
	<span>#<input type="text" value="ffffff"></span>	
</div>

Hope it helps :)