你会如何使用css / Javascript垂直对齐文本?

时间:2016-11-21 20:26:13

标签: javascript css text-justify

我们的网站上有一个div,想要在其中垂直地理解文本(不是垂直对齐或居中对齐)。

这是一个基本的例子(使用Bootstrap 3 +,btw):

<div class="row">
    <div class="col-xs-12 col-sm-4 v-justify">
        this is our text that we need verticlaly justified.  lorem ipsum dolor amet, etc...
    </div>
    <div class="col-xs-12 col-sm-4 portCell">
        This is a div with a responsive image in it so we don't know the height.
        For arguments sake we'll say 300px
    </div>
    <div class="col-xs-12 col-sm-4 portCell">
        This is a another div with a responsive image in it so we don't know the height.
        For arguments sake we'll say 300px
    </div>
</div>

我们怎样才能让第一个DIV中的文本垂直对齐。只有CSS解决方案的奖励点,具有适合媒体查询的样式,可提供全面的设备支持。


基于Andrew Rockwell的解决方案

的答案

这是按类(v-justify)循环的,所以我们可以将它应用到我们网站的多个区域。

$('.v-justify').each(function(){
    var justify = $(this);
    var maxHeight = justify.parent().next('.portCell').height();
    var fontSize = 1.5;
    while ( maxHeight > justify.height() ) {
          justify.css('font-size', (fontSize+=1.7) + 'px');
     }
});

2 个答案:

答案 0 :(得分:1)

这是怎么回事: https://jsfiddle.net/sp3rLang/4/

var justify = document.getElementById('v-justify');
var maxHeight = justify.parentElement.clientHeight;
var fontSize = 1;
while ( maxHeight > justify.clientHeight ) {
    justify.style.fontSize = fontSize++ + 'px';
}
// the while loop will always break a font size over the maxHeight
justify.style.fontSize = ( fontSize - 1 ) + 'px';

答案 1 :(得分:0)

CSS Flexbox使得内容与网格状结构的对齐比以前容易得多,但它有一点学习曲线。

如果您查看CSS评论,可以将space-around替换为space-between,以使内容触及其容器的顶部和底部,其余部分将在元素之间平均分配

并且,根据您的请求,可以根据需要在媒体查询中交换这些类。

&#13;
&#13;
       /* Flexbox is based on the concept that the flex "boxes"
           be inside of a container element.
        */
	      .flex-container {
	        border:3px solid green;
	        list-style:none;
	        display:flex; 
	        height:200px;
          width:500px;
          padding:0;
          margin:0;


          /* THIS IS WHAT GIVES US THE EVEN SPACING
             YOU CAN REPLACE "space-around" with "space-between"
             TO GET A SLIGHTLY DIFFERENT JUSTIFICATION   */
	      justify-content:space-around; 

          /* This gives us columns as opposed to rows: */
          flex-direction:column;
	      }

        /* ...and, then the container contains the
           flexbox items.
        */
	      .flex-item {
	         background:tomato;
	         font-weight:bold;
	         font-size:.7em;
	         text-align:center;
	         border:2px dashed black;
	         height:20px;
           width:100%;
	      }
&#13;
     <ul class="flex-container">
       <li class="flex-item one">One</li>
       <li class="flex-item two">Two</li>
       <li class="flex-item three">Three</li>
       <li class="flex-item four">Four</li>
     </ul>
&#13;
&#13;
&#13;