简体   繁体   中英

CSS - vertical align text and button

I have a jsfiddle here - https://jsfiddle.net/hjq6ay60/12/

Super simple, I always forget how to do this.

I have text floated left and a button floated right.

I just need to centre them both vertically - I'm sure you can do this with adding padding to the text.

.block{
    border: 1px solid red;
    padding: 10px;
    width: 400px;

    &-top{
        display: inline-block;
        float: left;
        vertical-align: middle;
    }

    &-bottom{
        float: right;
         vertical-align: middle;
        &__button{
            border: 1px solid grey;  
            height: 50px;
            width: 50px;
        }
    }
}

why don't you use display:table and display:table-cell ?? see here

.block {
   display:table;
}
.block-bottom,.block-top {
   display table-cell;
   vertical-align: middle;
}
.block-bottom {
   width: 50px;
}

and remove float:left and float:right from .block-bottom .block-top

We could make use of position and translateY this way:

.block {
  border: 1px solid red;
  padding: 10px;
  width: 400px;
  position: relative;               // Add here
  &-top {
    position: absolute;             // Add here
    top: 50%;                       // Add here
    left: 5px;                      // Add here
    right: 65px;                    // Add here
    transform: translateY(-50%);    // Add here
    p {
      margin: 0;
    }
  }
}

Preview

One Line: https://jsfiddle.net/xpgszmvn/
Multi Line: https://jsfiddle.net/zqxvwv8L/

Flexbox can do that for you, for free. Plus you get the added bonus of getting rid of the floats.

Example Here

.block{
    border: 1px solid red;
    padding: 10px;
    width: 400px;
    display: flex; align-items: center; /* Magic! */

    &-top{
      flex: 1; /* Stretch this item all the way */
               /* By default, items take only as much as they need */
    }

    &-bottom{
        /* No need for floats or display: */
        &__button{
            border: 1px solid grey;  
            height: 50px;
            width: 50px;
        }
    }
}

use height and line-height at equal values for example

button{
  height:30px;
  line-height:30px;
  text-align:center;
}

Always text will come in center

For two line text

 button{
   width:50px;
   height:auto;
   padding:10px;
}

This will create button with height depending on text

Try this, Surely work for you.

.block {
    display: table
}

.block-top {
    display: table-cell;
    vertical-align: middle;
}

.block-bottom {
    display: table-cell;
    width: 50px;
    vertical-align: middle;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM