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

高洛峰
Release: 2017-03-09 16:54:10
Original
1358 people have browsed it

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>
Copy after login

style is like this

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

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>
Copy after login

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;            
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template