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

我有一个元素,它是<div>元素的子元素,我想让子元素以<div>这个父元素居中,而不是整个窗口。

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


当前回答

首先,你可以用左:50%来相对于父div居中,但为此你需要学习CSS定位。

一个可能的解决方案是做一些像

    div.parent { text-align:center; }    //will center align every thing in this div as well as in the children element
    div.parent div { text-align:left;}   //to restore so every thing would start from left

如果你的div是居中相对定位,你可以这样做

    .mydiv { position:relative; margin:0 auto; } 

其他回答

<html>
<head>
</head>
<style>
  .out{
    width:200px;
    height:200px;
    background-color:yellow;
  }
   .in{
    width:100px;
    height:100px;
    background-color:green;
    margin-top:50%;
    margin-left:50%;
    transform:translate(-50%,50%);
  }
</style>
  <body>
     <div class="out">
     <div class="in">

     </div>
     </div> 
  </body>
</html>

text-align:中心;在父div应该做的把戏

有很多方法可以让元素居中,可以使用显示属性,位置,浮动,边距。但通常我更喜欢使用flexbox,因为它简单易用。我知道不同的人有不同的偏好,但这完全取决于开发人员的偏好和元素之间的关系。

.parent { 显示:块; } .sub-parent-1 { 显示:flex; justify-content:中心;/ /水平居中 对齐项目:中心;/ /垂直定心 } 身体< > < div class = "父" > < div class = " sub-parent-1”> < div class = " child-1 " >…< / div > < / div > < div class = " child-2 " >…< / div > < div class = " child-3 " >…< / div > < div class = " child-4 " >…< / div > < div class = " child-5 " >…< / div > < / div > 身体< / >

我喜欢魔法。

html, body {
 height: 100%;
}

.flex-container{
  display: -ms-flexbox;
  display: -webkit-box;
  display: flex;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -webkit-box-align: center;
  align-items: center;
  -webkit-box-pack: center;
  justify-content: center;
}


<div class="flex-container">
  <div>Content</div>
</div>

只以特定的子为中心:

.parent { 身高:100 px; 背景颜色:灰色; 位置:相对; } .child { 背景颜色:白色; 位置:绝对的; 上图:0; 底部:0; 左:0; 右:0; 宽度:20 px; 高度:20 px; 保证金:汽车; } < div class = "父" > < span class = "孩子" >你好> < /跨度 < / div >

或者,你也可以使用flex,但是那样会把所有的子节点居中

.parent { 身高:100 px; 背景颜色:灰色; 显示:flex; justify-content:中心; 对齐项目:中心; } .child { 背景颜色:白色; } < div class = "父" > < span class = "孩子" >你好> < /跨度 < / div >