Bootstrap how to get text to vertical align in a div container

前端 未结 3 1104
Happy的楠姐
Happy的楠姐 2020-12-29 05:03

What is the best/proper way to vertically align the text in the middle of its column? The image height is statically set in the CSS.

I have tried setting an outer di

相关标签:
3条回答
  • 2020-12-29 05:20

    HTML:

    First, we will need to add a class to your text container so that we can access and style it accordingly.

    <div class="col-xs-5 textContainer">
         <h3 class="text-left">Link up with other gamers all over the world who share the same tastes in games.</h3>
    </div>
    

    CSS:

    Next, we will apply the following styles to align it vertically, according to the size of the image div next to it.

    .textContainer { 
        height: 345px; 
        line-height: 340px;
    }
    
    .textContainer h3 {
        vertical-align: middle;
        display: inline-block;
    }
    

    All Done! Adjust the line-height and height on the styles above if you believe that it is still slightly out of align.

    WORKING EXAMPLE

    0 讨论(0)
  • 2020-12-29 05:22

    Could you not have simply added:

    align-items:center;
    

    to a new class in your row div. Essentially:

    <div class="row align_center">
    
    .align_center { align-items:center; }
    
    0 讨论(0)
  • 2020-12-29 05:23
    h2.text-left{
      position:relative;
      top:50%;
      transform: translateY(-50%);
      -webkit-transform: translateY(-50%);
      -ms-transform: translateY(-50%);
    }
    

    Explanation:

    The top:50% style essentially pushes the header element down 50% from the top of the parent element. The translateY stylings also act in a similar manner by moving then element down 50% from the top.

    Please note that this works well for headers with 1 (maybe 2) lines of text as this simply moves the top of the header element down 50% and then the rest of the content fills in below that, which means that with multiple lines of text it would appear to be slightly below vertically aligned.

    A possible fix for multiple lines would be to use a percentage slightly less than 50%.

    0 讨论(0)
提交回复
热议问题