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
505 views
in Technique[技术] by (71.8m points)

css - Vertically center content of floating div

How do I verically center the content of floating div (which height I don't know)?

There is very simple HTML and CSS (see this fiddle: http://jsfiddle.net/DeH6E/1/)

<div class="floating">
    This should be in the middle
</div>
?
.floating {
    height: 100px;
    float: left;
    border: 1px solid red;
    vertical-align: middle;
}   ?

How do I make the sentence "This should be in the middle" appear really in the middle (vertically centered)? vertical-align: middle does not seem to work. I have tried display: table-cell and it didn't work either. What's the best way to solve this issue? I'd like to avoid inserting any other HTML tags, do it just via CSS.

(Just to make it clear: I don't know the actual height of the container, 100px is just for the example)

EDIT: I'd like you to understand me, so... Always when I design web page, I follow the rule that HTML holds the content and CSS is responsible for the visual style. I never mix them up together or use one just to enable the other. In this case, I want to stick with this rule too. I don't want to insert HTML element just for the CSS.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The others are right, you need to nest two DOM elements which gives you more options controlling the centering. Here's the code:

.floating {
  display: table;
  float: right;
  height: 200px;
  width: 400px;
  border: 1px solid red;
}
.floating p {
  display: table-cell; 
  vertical-align: middle; 
  text-align: center;
}
<div class="floating">
    <p>This is the proper way that validates and breaks across multiple
    lines, if the text is longer than just a few words and still
    should be vertically centered. Here, it's also horizontally
    centered for added joy.</p>
</div>

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

...