Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

html - How to vertically center content of child divs inside parent div in a fluid layout

I have a div which contains two child divs, and they are intended to be part of fluid layout, so I can't set a fixed size for them in px.

There are two goals here:

  1. Align the two child divs horizontally, which I have achieved using float: left and float: right respectively.

  2. Vertically center the text (within the child divs) relative to the parent div. The text is short and takes a single line by design.

What I have now: http://jsfiddle.net/yX3p9/

Apparently, the two child divs do not take the full height of the parent div, and therefore their text are not vertically centered relative to the parent div.

Conceptually, to achieve the goals above, we can either make the child divs vertically centered within the parent div, or we can make the child divs take the full height of the parent div. What is the robust way to do so?

*Browser support: IE 9+ and other usual modern browsers.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I prefer the usage of transform above the above answers.

top: 50%;
transform: translateY(-50%);
-ms-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-webkit-transform: translateY(-50%);
-o-transform: translateY(-50%);

In my experience it works in many situations and on all major browsers (even IE9+).

If you use SCSS, you might even like to implement this mixin:

@mixin v-align($position: absolute){
    position: $position;  top: 50%;  
    transform: translateY(-50%);
    -ms-transform:translateY(-50%); /* IE */
    -moz-transform:translateY(-50%); /* Firefox */
    -webkit-transform:translateY(-50%); /* Safari and Chrome */
    -o-transform:translateY(-50%);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...