Search code examples
htmlcssbuttonalignmentvertical-alignment

How to align a button contained within a div central and bottom?


I have created three identical boxes (other than the description length contained within the p tag) containing an icon, title, description and button using the following HTML code:

    .coursebutton {
    display: inline-block;
    border-radius: 4px;
    background-color: #009ada;
    border: none;
    color: #FFFFFF;
    text-align: center;
    font-family: 'Raleway', sans-serif;
    text-transform: uppercase;
    font-size: 13px;
    padding: 9px;
    width: 100px;
    transition: all 0.5s;
    cursor: pointer;
    }
    <div class="col_one_third col_one_third_even">
    	<div class="feature-box fbox-plain">
    		<div class="fbox-icon">
    			<img src="images/am-icon.png"/>
    		</div>
    		<h3>ADVERTISING AND MEDIA</h3>
    		<p>Example example example example example example example example example example example example </p>
    		<button class="coursebutton" onclick="window.location.href = 'courseinfo/am.html';"><span>Details </span></button>
    	</div>
    </div>

How can I make the buttons always sit at the bottom of the box and in the center no matter how much text is within the p element?


Solution

  • Just add relative position, a left of 50% and a translateX of -50% to your code. Regardless of text size, the button will always be centered.

    You need the translate because the CSS left property is based on the size of the parent element and the transform property is based on the size of the target element. Using both you get the content completely centered in their parent.

    .coursebutton {
      display: inline-block;
      border-radius: 4px;
      background-color: #009ada;
      border: none;
      color: #FFFFFF;
      text-align: center;
      font-family: 'Raleway', sans-serif;
      text-transform: uppercase;
      font-size: 13px;
      padding: 9px;
      width: 100px;
      transition: all 0.5s;
      cursor: pointer;
      position: relative;
      left: 50%;
      transform: translateX(-50%);
    }
    

    Example here

    EDIT 1

    To get the buttons to be on the same level in different blocks, we need the blocks to be the same height. For this we can use something like javascript equalHeigh. Although for me the best option is to use flexbox.

    https://jsfiddle.net/uugmvcvm/