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

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

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


当前回答

如果子元素是内联的(例如不是一个div,表格等),我会把它包装在一个div或一个p,并使包装器的文本对齐css属性等于中心。

    <div id="container">
        This text is aligned to the left.<br>
        So is this text.<br>
        <div style="text-align: center">
            This <button>button</button> is centered.
        </div>
        This text is still aligned left.
    </div>

否则,如果元素是一个具有固定宽度的块(显示:块,例如div或p),我将其左距和右距css属性设置为auto。

    <div id="container">
        This text is aligned to the left.<br>
        So is this text.<br>
        <div style="margin: 0 auto; width: 200px; background: red; color: white;">
            My parent is centered.
        </div>
        This text is still aligned left.
    </div>

当然,您也可以向wrapper元素添加text-align: center,使其内容也居中。

我不会费心定位,因为依我之见,这不是OPs问题的解决方法,但一定要查看这个链接,非常有用。

其他回答

我喜欢魔法。

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>

text-align:中心;在父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 >

<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>

如果你想使用CSS3:

position:absolute;
left:calc(50% - PutTheSizeOfTheHalfOfYourElementpx);

您可能需要做进一步的搜索,以弄清楚如何使百分比适合元素的宽度。