Search code examples
htmlcsspositiontransform

How can I center text without it staying at the top it's containing element?


I have been attempting to use vertical-align: middle and text-align: center to center the button, but it does not affect my styling at all and the button stays at the top.

I am not sure why the style is not being applied. I can use top: 50%, but that is not the true center depending on the amount of text the button will contain.

#selectmanager-outer {
    width: 200px;
    height: 200px;
    float: left;
    box-sizing: border-box;
    padding: 10px;
}

 #selectmanager-inner {
    height: 150px;
    box-sizing: border-box;
    border: 1px solid #E0E0E0;    
    background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#F5F5F5), to(#FAFAFA));
    background-image: -webkit-linear-gradient(#F5F5F5, #FAFAFA);
    background-image: -moz-linear-gradient(#F5F5F5, #FAFAFA);
    background-image: -o-linear-gradient(#F5F5F5, #FAFAFA);
    background-image: linear-gradient(#F5F5F5, #FAFAFA);
    padding: 10px;
}
<div id='selectmanager-outer'>
    <div id ='selectmanager-inner'>
        <button>Very long button name to test</button>
    </div>
</div>

Solution: With the assistance of Akheel K M's answer with the use of position, percentages, and transforms.

#selectmanager-outer {
  width: 200px;
  height: 200px;
  float: left;
  box-sizing: border-box;
  padding: 10px;
}

#selectmanager-inner {
  height: 150px;
  box-sizing: border-box;
  border: 1px solid #E0E0E0;	
  border-radius: 30px 30px;	
  background: #F5F5F5;
  background-image: -webkit-linear-gradient(top, #F5F5F5, #FAFAFA);
  background-image: -moz-linear-gradient(top, #F5F5F5, #FAFAFA);
  background-image: -ms-linear-gradient(top, #F5F5F5, #FAFAFA);
  background-image: -o-linear-gradient(top, #F5F5F5, #FAFAFA);
  background-image: linear-gradient(to bottom, #F5F5F5, #FAFAFA);
  padding: 10px;
  position: relative;
}

#selectmanager-inner button {
  position: absolute; 
  top: 50%; 
  left: 50%; 
  transform: translateY(-50%) translateX(-50%);
}
<div id='selectmanager-outer'>
  <div id ='selectmanager-inner'>
    <button>Very long button name to test</button>
  </div>
</div>


Solution

  • Why don't you try transform: translateY(-50%); after you do top:50%;?Probably won't work on older browsers.