简体   繁体   中英

Center text in fixed height div, text without break

The div always has a fixed height. The text in it should always be centered. As soon as the text becomes larger than the div, the font-size should become smaller so that the text is centered in the div. The problem is, I can not add different classes to the headings. Has anyone an idea how I can solve this? Do I need javascript? Any help will be appreciated. Thank You.

 .fix-height{ height: 60px; width: 270px; border: 1px solid #000000; display: table-cell; vertical-align: middle; text-align: center; } h2{ font-size: 20px; } 
 <div class="fix-height"> <h2>Lorem ipsum dolor sit Lorem ipsum dolor sit</h2> </div> <br><br><br><br> <div class="fix-height"> <h2>Lorem ipsum dolor sit</h2> </div> <br><br><br><br> <div class="fix-height"> <h2>Lorem ipsum dolor sit Lorem ipsum dolor sit Lorem ipsum dolor sit</h2> </div> 

You can do it with simple JQuery

Here is the code:

 $(function() { $('#fitin div').css('font-size', '1em'); while ($('#fitin div').height() > $('#fitin').height()) { $('#fitin div').css('font-size', (parseInt($('#fitin div').css('font-size')) - 1) + "px"); } }); 
 #fitin { width: 300px; height: 200px; line-height: 200px; border: 1px solid black; overflow: hidden; font-size: 1em; text-align: center; } #fitin div { display: inline-block; vertical-align: middle; line-height: normal; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="fitin"> <div>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div> </div> 

EDIT Aligned the text in center

FitText is a Javascript-Library i used in past projects. You can define a range of font-sizes and it takes the biggest one possible.

add css

.fix-height{
display: table-cell;
    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