- To center the div : remove the float.
- So that the width automatically matches the size of the text : display: inline-block;
No need to change anything in .one
!
Run the snippet to see it in action.
.one{
height: 66px;
line-height: 36px;
text-align: center;
margin: 0 auto;
}
.two{
background-color: #3498db;
color: white;
font-size: 24px;
padding-top: 15px;
padding-bottom: 15px;
padding-left: 20px;
padding-right: 20px;
display:inline-block;
}
<div class="one">
<div class="two">start now</div>
</div>
<p>Width changes automatically:, e.g. </p>
<div class="one">
<div class="two">Another div with longer text</div>
</div>
Run codeHide resultFloat takes items out of the page stream, so they cannot be positioned. Do not use a float unless you really want to float it!
source
share