CSS:<div> 元素中的中心元素

新手上路,请多包涵

要使 HTML 元素居中,我可以使用 CSS left: 50%; 。但是,这会使元素相对于整个窗口居中。

我有一个元素,它是 <div> 元素的子元素,我想将子元素相对于这个父 <div> ,而不是整个窗口。

我不希望容器 <div> 将其 所有 内容居中,只是一个特定的孩子。

原文由 Randomblue 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 338
2 个回答

text-align:center; 设置为父 div,将 margin:auto; 设置为子 div。

 #parent {
    text-align:center;
    background-color:blue;
    height:400px;
    width:600px;
}
.block {
    height:100px;
    width:200px;
    text-align:left;
}
.center {
    margin:auto;
    background-color:green;
}
.left {
    margin:auto auto auto 0;
    background-color:red;
}
.right {
    margin:auto 0 auto auto;
    background-color:yellow;
}
 <div id="parent">
    <div id="child1" class="block center">
        a block to align center and with text aligned left
    </div>
    <div id="child2" class="block left">
        a block to align left and with text aligned left
    </div>
    <div id="child3" class="block right">
        a block to align right and with text aligned left
    </div>
</div>

这是一个很好的资源来集中任何东西。

http://howtocenterincss.com/

原文由 pasine 发布,翻译遵循 CC BY-SA 4.0 许可协议

实际上,这对于 CSS3 flex boxes 来说非常简单。

 .flex-container{
  display: -webkit-box;  /* OLD - iOS 6-, Safari 3.1-6, BB7 */
  display: -ms-flexbox;  /* TWEENER - IE 10 */
  display: -webkit-flex; /* NEW - Safari 6.1+. iOS 7.1+, BB10 */
  display: flex;         /* NEW, Spec - Firefox, Chrome, Opera */

  justify-content: center;
  align-items: center;

  width: 400px;
  height: 200px;
  background-color: #3498db;
}

.inner-element{
  width: 100px;
  height: 100px;
  background-color: #f1c40f;
}
 <div class="flex-container">
  <div class="inner-element"></div>
</div>

更新:

看来我在写这个答案时没有阅读 OP 编辑。 上面的代码将使所有内部元素居中(它们之间没有重叠),但 OP 只希望将特定元素居中,而不是其他内部元素。所以@Warface 回答第二种方法更合适,但它仍然需要垂直居中:

 .flex-container{
  position: relative;

  /* Other styling stuff */
  width: 400px;
  height: 200px;
  background-color: #3498db;
}

.inner-element{
  position: absolute;
  left: 50%;
  top: 50%;

  transform: translate(-50%,-50%);
  /* or 3d alternative if you will add animations (smoother transitions) */
  transform: translate3d(-50%,-50%,0);

  /* Other styling stuff */
  width: 100px;
  height: 100px;
  background-color: #f1c40f;
}
 <div class="flex-container">
  <p>Other inner elements like this follows the normal flow.</p>
  <div class="inner-element"></div>
</div>

原文由 Gerard Reches 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题