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

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

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


当前回答

只需要给出父div的位置:relative

其他回答

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

我相信现代的方法是在父容器中放置位置-项目:居中

一个例子可以在这里找到:https://1linelayouts.glitch.me

如果这些答案都没有,那就对了。试试这个。 水平和垂直对齐的子元素。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <div class="container">
            <div class="content">
                <img width="300px" src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/30/Building92microsoft.jpg/800px-Building92microsoft.jpg" alt="microsoft" />
            </div>
        </div>
    </body>
    <style>
        .container {
            display: flex; /* can also use grid */
            background-color: #47472d;
            width: 500px;
            height: 400px;
            overflow: auto;
        }
        .content { margin: auto; }
    </style>
</html>

我喜欢魔法。

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>