[英]make center the second child element inside a parent div width float child element
我有這個html結構。
<div id="parent">
<div class="child">
<h1>title</h1>
<p>content</p>
</div>
<div class="child">
<h1>title</h1>
<p>content</p>
</div>
<div class="child">
<h1>title</h1>
<p>content</p>
</div>
</div>
以及這些元素的CSS。
#parent{
padding: 0px 8px;
overflow: auto;
max-width: 100%;
max-height: 100%;
}
.child{
width: 300px;
display: block;
}
.child:first-child{
float: left;
}
.child:last-child{
float: right;
}
.child:nth-child(2){
/* what is the style here to make it center? */
}
從上面的代碼中可以看到,目標是使這些子元素以整齊干凈的方式正確對齊,因此第一個子元素向左浮動,最后一個子元素向右浮動,第二個子元素應恰好位於這些左,右子元素,因此我要實現的是在父div內等距排列的三個框。 到目前為止,我嘗試了margin:0 auto; 在中間子元素上,但不幸的是無法正常工作,因此目前我正在尋找一種精確的解決方案以實現所需的輸出。
只要浮動它:
#parent{
padding: 0px 8px;
overflow: auto;
max-height: 100%;
float:left;
width:900px;
}
.child{
width: 300px;
display: block;
float:right;
}
將第二個div浮動到左側,並在需要時向左側應用邊距。 如果您嘗試創建自適應模板,只需使用%而不是像素。 我希望這是有道理的。
.child:first-child, .child:nth-child(2) {
float:left;
}
.child:nth-child(2) {
/* what is the style here to make it center? */
margin-left: what ever pixels or %;
}
.child:last-child {
float:right;
}
JSFIDDLE(響應式):
您不需要將元素相互浮動,您需要的是使用display: inline-block property
在它們上,這是一種駭人但更干凈的方法:
#parent{
width: 100%;
height: 100%;
max-width: 100%;
max-height: 100%;
overflow: hidden;
}
.child{
width: 33%; // Since there are 3 childs.
display: inline-block;
}
這里的技巧和竅門是,您需要注釋HTML代碼中子元素之間的空間,因為屬性display:inline-block
僅對齊沒有空格的元素,因此html代碼應如下所示:
<div id="parent">
<div class="child">
<h1>title</h1>
<p>content</p>
</div><!--
--><div class="child">
<h1>title</h1>
<p>content</p>
</div><!--
--><div class="child">
<h1>title</h1>
<p>content</p>
</div>
</div>
~
這是鏈接到的jsfiddle 檢查出來
〜
〜
好的,因為您也標記了jquery,所以這是JQ方式。
如果您不想將固定寬度設置為#parent
並且想要將固定寬度設置為.child
,請使用此選項。 也可以在跨瀏覽器和舊瀏覽器中使用。
演示http://jsfiddle.net/yeyene/VW9mw/
$(document).ready(function(){
moveCenter();
$(window).resize(function() {
moveCenter();
});
});
function moveCenter(){
var mar = ($('#parent').width()-$('.child').width()*3)/2;
$('.child').eq(1).css({
'margin-left': mar+'px',
'margin-right':mar+'px'
});
}
Flexbox使這個瑣碎的事:
#parent {
display: flex;
}
.child {
flex: 1;
}
根據需要添加前綴和較早的語法,符合http://caniuse.com/#search=flexbox
我為您提供了一個示例: http : //codepen.io/anon/pen/tribL
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.