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

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

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


当前回答

设置text-align:中心;到父div,页边距: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/

其他回答

指定text-align: center;到父对象并显示:inline-block;到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>
<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>

我找到了另一个解决办法

<style type="text/css">
    .container {
        width:600px; //set how much you want
        overflow: hidden; 
        position: relative;
     }
     .containerSecond{
        position: absolute; 
        top:0px; 
        left:-500%; 
        width:1100%;
     }
     .content{
        width: 800px; //your content size 
        margin:0 auto;
     }           
</style>

在身体上

<div class="container">
   <div class="containerSecond">
       <div class="content"></div>
   </div>
</div>

这将在容器变大或变小时将内容div居中。在这种情况下,你的内容应该大于容器的1100%才能不居中,但在这种情况下,你可以让with of containerSecond更大,这样就可以了

弯曲后,它显示文章

.container { 显示:flex; 颜色:蓝色; 背景颜色:黄色; justify-content:中心; } < div class = "容器" > < div > < / div元素> < / div > 如果你水平和垂直地设置元素中心。

.container { 显示:flex; 颜色:蓝色; 身高:100 px; 背景颜色:黄色; justify-content:中心; 对齐项目:中心; } < div class = "容器" > < div > < / div元素> < / div >