Home  >  Article  >  Web Front-end  >  Detailed explanation of CSS implementation of vertical centering within a div with fixed width and height. Example sharing

Detailed explanation of CSS implementation of vertical centering within a div with fixed width and height. Example sharing

高洛峰
高洛峰Original
2017-03-09 16:54:101362browse

This article mainly introduces the detailed example of CSS vertical centering within p with fixed width and height, that is, the method of vertically centering elements inside p relative to p. Friends in need can refer to it

Requirement Case

The case is like this. The height and width of an outer p are fixed, but the content inside is not fixed. What many friends do is to add a padding or margin to the head, so that the content inside appears to be centered. However, if the content changes, the fixed padding or margin of the head will never change. As a result, the vertical direction will not be centered!

We know that if the following p

<p class="outer"><p class="inner">haorooms内部内容</p></p>

style is like this

.outer{text-align:center;vertical-align: middle;width:200px;height:350px;}

vertical-align:middle does not matter Many friends have made a fuss about .inner, adding margin, etc. as I mentioned above! So is there a better solution for this situation?

Solution

Idea: Add a cssHack, set the line-height of cssHack equal to the height of the outer p, and you can use vertical-align:middle!

p is as follows:

<p class="outer">   
    <p class="inner">haorooms内部内容</p><p class="v">cssHack</p>   
</p>

The style is as follows:

* {   
    margin: 0;   
    padding: 0;   
}   
.outer {   
    background-color: #ccc;   
    font-size: 24px;   
    height: 350px;   
    text-align: center;   
    overflow: hidden;   
    width: 280px;   
}   
.outer  .inner,   
.outer  .v {   
    display: inline-block;   
    zoom: 1;*display: inline; /* 用于触发支持IE67 inline-block */
}   
.outer  .inner {               
    line-height: 1.8;   
    padding: 0 4px 0 5px;   
    vertical-align: middle;   
    width: 262px;              
}   
.outer  .v {   
    line-height: 350px;   
    text-indent:-9999px;   
    width: 1px;            
}

This achieves vertical centering inside p!

The above is the detailed content of Detailed explanation of CSS implementation of vertical centering within a div with fixed width and height. Example sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn