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

我有一个元素,它是<div>元素的子元素,我想让子元素以<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>

其他回答

首先,你可以用左: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; } 

如果你想在div中居中,不关心除法大小,你可以使用Flex功能。我更喜欢使用flex,不使用元素的精确大小。

<div class="outer flex">
    <div class="inner">
        This is the inner Content
    </div>
</div>

如你所见,Outer div是Flex容器,Inner必须是Flex项目,指定Flex: 1 1 auto;为了更好地理解,您可以看看这个简单的示例。http://jsfiddle.net/QMaster/hC223/

希望这对你有所帮助。

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

左:50%分别工作到最近的父静态宽度分配。尝试宽度:500px或在父div。或者,让你需要的内容居中显示:块,并设置左右边距为auto。

弯曲后,它显示文章

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

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