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

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

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


当前回答

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

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

其他回答

为您的元素创建一个新的div元素居中,然后添加一个类专门为该元素居中,如下所示

<div id="myNewElement">
    <div class="centered">
        <input type="button" value="My Centered Button"/>
    </div>
</div>

Css

.centered{
    text-align:center;
}

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

如果子元素是内联的(例如不是一个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问题的解决方法,但一定要查看这个链接,非常有用。

我找到了另一个解决办法

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

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

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