Home > Article > Web Front-end > Remember the centering we struggled with? _html/css_WEB-ITnose
Although the problem of centering content in divs is an old topic, recently I found that many front-end developers are still asking how to achieve it. In fact, there are already a lot of information and cases on the Internet. I will summarize a few more common handling methods here.
1 .v-align {2 margin: 0 auto;3 width: 200px;4 height: 80px;5 text-align: center;6 line-height: 80px;7 border: 1px solid #ddd;8 }
1 <div class="v-align">我的内容只能有一行。</div>
1 .v-mult { 2 margin: 0 auto; 3 width: 200px; 4 height: 100px; 5 border: 1px solid #ddd; 6 overflow: hidden; 7 } 8 .v-mult .empty, 9 .v-mult .text {10 display: inline-block;11 *display: inline;12 *zoom: 1;13 vertical-align: middle;14 }15 .v-mult .empty {16 height: 100%;17 }
1 <div class="v-mult">2 <span class="empty"></span>3 <span class="text">我的内容不限,多高都行<br>换行照常</span>4 </div>
1 .v-auto { 2 position: relative; 3 margin: 0 auto; 4 width: 200px; 5 border: 1px solid #ddd; 6 } 7 .v-auto .text { 8 position: absolute; 9 top: 50%;10 margin-top: -50px;11 height: 100px;12 border: 1px dashed #ddd;13 }
1 <div class="v-auto">2 <div class="text">3 我的高度是固定的,只有100px高,但是我的父及高度不定,我怎么垂直居中呢?4 </div>5 <br><br><br><br><br><br><br><br>6 </div>
1 .v-auto-out { 2 position: relative; 3 margin: 0 auto; 4 width: 200px; 5 border: 1px solid #ddd; 6 } 7 .v-auto-out .auto-in { 8 position: absolute; 9 top: 50%;10 border: 1px dashed #ddd;11 /* 这里有兼容性问题 */12 -webkit-transform: translateY(-50%);13 -ms-transform: translateY(-50%);14 -o-transform: translateY(-50%);15 transform: translateY(-50%);16 }
1 <div class="v-auto-out">2 <div class="auto-in">我的高度不定,我的父及高度也不定,这下要上下居中,该如何是好?我们一起来瞧瞧吧。</div>3 <br><br><br><br><br><br><br><br><br>4 </div>
Okay, knowing these four methods, I believe it is enough to deal with various vertical centering problems in daily work. The code is very simple, no need to elaborate further. In a word, the various attribute styles of CSS are like the various organs of the human body. Only by understanding the functions of each organ can we cooperate with each other to complete various tasks. On the contrary, individual abilities are limited.
Author blog: http://www.seejs.com