簡體   English   中英

CSS圖像/內容超過2 <div> 並垂直居中

[英]css image/content over 2 <div> and vertically centered

我需要將html頁面的背景一分為二(水平)。 頂部和底部將具有不同的背景圖像/紋理,將重復該背景圖像/紋理,換句話說,可以隨窗口的大小擴展。 在此“拆分背景”之上,我想顯示一些內容,例如文本或圖像。

這段代碼會生成我想要的“分割背景”,但是我不知道如何將內容放在上面。

<html>
<head>
<style type="text/css">
html{height: 100%;}
body { width: 100%; height: 100%; }
.top { width: 100%; height: 50%; background-image:url('img/top.jpg'); }
.bottom { width: 100%; height: 50%; background-image:url('img/bottom.jpg'); }
</style>
</head>

<body>
<div class="top"></div>
<div class="bottom"></div>
</body>

</html>

內容應在此“拆分背景”的頂部垂直並水平居中。 我嘗試使用第三個div,使用z-indexes並使用css3多bg功能,但是我無法獲得想要的結果。 有什么建議么?

使用position:fixed示例:
http://jsfiddle.net/LBQbb/3/

若要垂直居中放置高度未知的內容,可以使用以下技術:
http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

好的,最后我找不到CSS解決方案。 如果瀏覽器窗口太小,我放在其他2個div上的內容圖像將無法正確對齊...

我使用一些JavaScript解決了該問題,因為我開發的網站已經包含Javascript,所以這不是問題。

這是html:

<html>
<head>
<link href="css/reset-min.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">

    <script type="text/javascript" src="js/jquery-1.6.4.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function(){

            $(window).resize(function(){

                $('.content').css({
                    position:'absolute',
                    left: ($(window).width() 
                      - $('.content').outerWidth())/2,
                    top: ($('body').height() 
                      - $('.content').outerHeight())/2
                });

            });

       //To initially run the function:
       $(window).resize();

    });
    </script>

</head>

<body onload="$(window).resize()"> <!-- needed to correct loading bug -->

    <div class="top"></div>
    <div class="bottom"></div>

    <div class="content">
         <img alt="Content" src="img/01_illustration.png" /> 
    </div>
</body>
</html>

和CSS:

html, body { width:100%; height: 100%; }

body { min-height: 768px; min-width: 1024px; }


.top { width: 100%; height: 50%; background-image:url('img/01_texture_top.jpg'); }
.bottom { width: 100%; height: 50%; background-image:url('img/01_texture_bottom.jpg'); }

.content {}

只需創建第三個div。 之后,它應該顯示在頂部,而不需要z-indexs。

<html>
<head>
<style type="text/css">
html{height: 100%;}
body { width: 100%; height: 100%; min-width:950px; min-height: 950px;}
.top { width: 100%; height: 50%; background-image:url('img/top.jpg'); }
.bottom { width: 100%; height: 50%; background-image:url('img/bottom.jpg'); }
.third { position: absolute; top:50%; left:50%; width: 900px; margin-left: -450px; margin-top: -450px; }
</style>
</head>

<body>
<div class="top"></div>
<div class="bottom"></div>
<div class="third"> add content here</div>
</body>

添加絕對位置並將其設置為top,left =(0,0),之后可以毫無問題地使用它。 忽略其他為背景賦予顏色的div。

編輯:

固定回答您的評論。 這樣,它將創建一個始終位於屏幕中間居中的900px x 900px的框。

暫無
暫無

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

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