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

html - Why does margin: auto only work horizontally and not vertically?

I have seen that while developing websites, vertically centering a container (of fixed height) inside a container of random height always comes as a nightmare for the web developer (at least, me) while when it comes to horizontal centering a container (of fixed width) inside a container of random width, the margin:0px auto; tends to serve an easy way out in the standard model.

When things can be as simple as that why doesn't CSS work out with the margin:auto 0px; when it comes to centering a container of fixed height inside a container of random height? Is there any specific reason to do so?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

It's really less of a nightmare than you think, just don't use margins. vertical-align is really what you should rely on for fluid-height vertical centering. I threw together a quick demo to demonstrate my point:

* {
  margin: 0;
  padding: 0;
}

html,
body {
  height: 100%;
  text-align: center;
}

span {
  height: 100%;
  vertical-align: middle;
  display: inline-block;
}

#any-height {
  background: #000;
  text-align: left;
  width: 200px;
  height: 200px;
  vertical-align: middle;
  display: inline-block;
}
<span></span>
<div id="any-height"></div>

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

1.4m articles

1.4m replys

5 comments

56.9k users

...