![](/img/trans.png)
[英]How to align all child elements left when parent is aligned to the center- CSS
[英]Align one child element to the left when parent aligns all child elements to the center
我有一个DIV设置将所有子元素CENTER与text-align: center;
但我希望其中一个子元素与左边对齐,同时保持其余部分居中。
我怎样才能做到这一点?
我试图向左浮动那个元素,但它搞砸了我的设计,因为我根本不使用浮动。
.parent {
text-align: center;
margin-bottom: 15px;
margin-top: 8px;
}
.child (I want to align this one left) {
display: inline-block;
font-family: 'Source Sans Bold', Helvetica neue, verdana, arial;
font-size: 16px;
background-color: #5a8da3;
padding: 4px;
}
有很多方法可以做到这一点。 但是在与未来代码集成时,尝试用这个要求可视化您未来的一些问题。 最好的方法是使用不同的位置。
您希望父级的所有div元素在特定的位置与中心区别开来。 如果你没有给你想要的左边一个div显示属性,它将不遵守父的CSS规则: text-align:center;
我在所有想要居中的div元素上使用了display属性但是我设置了CSS规则: position:relative; 到了父母。 这将迫使所有子div具有位置:绝对; 受父母约束。 因此,我可以将属性的顶部和左侧设置为我想要放在左边的子div,这些属性将根据父宽度而不是浏览器的窗口计算。
这是最好的解决方案,因为定位绝对的子div不会影响结构化模板,因此在将来添加更多时,不会将居中的div推离父级的中心。
这是你的例子:
您现在可以使用CSS属性移动左侧div:top,left,bottom,right。
.parent {
background:#fefefe;
padding:5px;
border:1px solid black;
text-align:center;
position:relative;
}
.centerd {
border:1px solid green;
background:gold;
padding:90px;
display:inline-block;
}
.left {
padding:40px;
border:1px solid red;
background:orange;
width:40px;
position:absolute;
left:0;
top:20px;
}
工作范例:
http://jsfiddle.net/852ewccc/2/
我用了一个float: left
的div, margin: 0 auto;
把另一个div居中
HTML:
<div id="parent">
<div id="left">
</div>
<div id="center">
</div>
</div>
CSS:
#parent{
width: 500px;
height: 100px;
background: blue;
}
#center{
margin: 0 auto;
width: 200px;
height: 50px;
background: green;
}
#left{
width: 100px;
background: orange;
height: 30px;
}
JSFiddle: http : //jsfiddle.net/wafoyyLz/
Float将是最好的选择,你应该考虑让你的其他元素浮动,但如果你只想要文本对齐一个特定的元素:
HTML:
<div class="parent">
<div class="children"> Child 1 </div>
<div class="children"> Child 2 </div>
<div class="children alignLeft"> Child 3 </div>
<div class="children"> Child 4 </div>
<div class="children"> Child 5 </div>
</div>
CSS:
.parent {
border: 1px solid #000;
text-align: center;
margin-bottom: 15px;
margin-top: 8px;
}
.alignLeft {
background-color: #5a8da3;
text-align: left;
}
这样做可以让你通过硬编码或使用JQuery的add / remove类将类添加到其他子节点。
请记住,这不适用于所有类型的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.