簡體   English   中英

用margin:auto定位div左右的元素

[英]positioning elements left and right of a div with margin:auto

我有一個以設置的寬度(以像素為單位)以margin: auto;為中心的div margin: auto; 如何將元素的寬度動態調整到該div的左邊或右邊,以適應中心div的邊距?

謝謝你的幫助!

編輯:更多信息...

基本上,它是以下設置:

<div></div>
<div style="margin:auto; width: 950px">content goes here</div>
<div></div>

我想在中心div的左側和右側具有相同的背景圖像,但在中心div上具有不同的背景圖像。 因此,如何將左div和右div與中心div的左右對齊,並使其寬度覆蓋中心div的整個邊距。

如果只是背景,您可以這樣做:

<div style="background: url('path/to/image.jpg'); background-size: cover; position: absolute; left: 0; top: 0; right: 0; bottom: 0;">
  <div style="margin:auto; width: 950px">content goes here</div>
</div>

它將背景投影到背景div上。 然后,在內部div上,您可以指定另一個背景,該背景將超過父div的背景。

這也應該工作...我已經將寬度減小了(以適合jsfiddle http://jsfiddle.net/Neograph734/Vb4Hm/1/ )。 如果您應該同時編輯左邊距。

<div style="margin:auto; width: 250px; background: red;">    
  <div id="left_sidebar" style="float: left; width: 200px; margin-left: -200px;">
    <div id="right_sidebar" style="float: left; width: 200px; margin-left: 450px;">

    </div>
  </div>

Content here

</div>

更新:內容應在浮動div下方

解決方案1:

可以通過table輕松解決此問題,就像這樣使用

<table width="100%">
   <tr>
       <td background="your/image/url5">content...</td>
       <td width="950" background="your/image/url">content goes here...</td>
       <td background="your/image/url5">content...</td>
  </tr>
</table>

您可以使用所有三個塊來編寫內容,也可以使用不同的內容

解決方案2:

如果需要div ,則需要為此編寫一些jQuery

html:

<div class="left"></div>
<div class="center">content goes here...</div>
<div class="right"></div>

css:

<style>
.left{
    background:url(your/image);
    float:left;
}
.center{
    background:url(your/image);
    float:left;
    width:950px;
}
.right{
    background:url(your/image);
    float:left;
}
</style>

jQuery的:

<script type="text/javascript">
    var window_width = $(window).width(); // get window width
    var total_remain = $(window).width()-950; // (-) your center div width
    var apply_width = total_remain / 2; // get remaining and divide by 2
    $(".left").css("width","apply_width"); // appying the width to the right / left
    $(".right").css("width","apply_width"); // appying the width to the right / left
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM