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

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

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


当前回答

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

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

其他回答

我找到了另一个解决办法

<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更大,这样就可以了

实际上,这在CSS3 flex boxes中是非常简单的。

.flex-container{ display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6, BB7 */ display: -ms-flexbox; /* TWEENER - IE 10 */ display: -webkit-flex; /* NEW - Safari 6.1+. iOS 7.1+, BB10 */ display: flex; /* NEW, Spec - Firefox, Chrome, Opera */ justify-content: center; align-items: center; width: 400px; height: 200px; background-color: #3498db; } .inner-element{ width: 100px; height: 100px; background-color: #f1c40f; } <div class="flex-container"> <div class="inner-element"></div> </div>

更新:

似乎我在写这个答案的时候没有阅读OP编辑。上面的代码将所有内部元素居中(它们之间没有重叠),但是OP只希望一个特定的元素居中,而不是其他内部元素。所以@Warface回答第二种方法更合适,但仍然需要垂直居中:

.flex-container{ position: relative; /* Other styling stuff */ width: 400px; height: 200px; background-color: #3498db; } .inner-element{ position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); /* or 3d alternative if you will add animations (smoother transitions) */ transform: translate3d(-50%,-50%,0); /* Other styling stuff */ width: 100px; height: 100px; background-color: #f1c40f; } <div class="flex-container"> <p>Other inner elements like this follows the normal flow.</p> <div class="inner-element"></div> </div>

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

你可以像这样使用bootstrap flex类名:

<div class="d-flex justify-content-center">
    // the elements you want to center
</div>

即使里面有很多元素也可以。

例如,我有一个文章div里面的主要内容div.. 在文章里面有一个图片,图片下面是一个按钮,样式如下:

.article {

width: whatever;
text-align: center; 
float: whatever (in case you got more articles in a row); 
margin: give it whatever margin you want;

} .article {

}

/*在文章里面,我想让图像居中*/

文章{

float: none;
margin: 0 auto;
padding: give it a padded ridge if you want;

}

/*现在,在同一article元素的这张图片下,应该有一个按钮,如阅读更多。当然,当它在响应式设计中时,你需要使用em或%

.button {

background: #whatever color:
padding: 4.3567%; /*Instead of fixed width*/
text-align: cente;
font: whatever;
max-width: 41.4166%;
float: none;
margin: 0 auto; /* You could make the zero into any margin you want on the top and bottom of this button.. Just notice the float: none property.. this wil solve most your issues, also check if maybe position and displaay might mess up your code..*/

}

祝你好运