【问题标题】:Positioning DIVs with CSS使用 CSS 定位 DIV
【发布时间】:2013-04-11 17:33:14
【问题描述】:

我在彼此内部有两个 DIV。内部 DIV 包含一个图像。我正在尝试在右上角的该图像上添加一个浮动文本。我不知道如何使该文本使用内部 DIV 的位置而不是外部位置。

这是我目前得到的结果

CSS:

html {
    background: #EEF0F3;
}
.outer {
    background: #FFFFFF;
    border-radius: 4px 4px 4px 4px;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
    margin: 0 auto;
    padding:20px 0px;
    position: relative;
    width: 680px;
    text-align: center;
    margin-bottom: 20px;
}
.inner {
    position: relative;
}
h2 { 
   position: absolute; 
   top: 0px; 
   right: 0px; 
}
h2 span { 
   color: white; 
   font: bold 24px Helvetica, Sans-Serif; 
   letter-spacing: -1px;
   background: rgba(255, 0, 0, 0.5);
   padding: 0px 10px; 
}

HTML:

<div class="outer">
    <div class="inner">
        <h2><span>Title 1</span></h2>
        <img src="1.jpg">
    </div>
</div>

这是JSFiddle中的代码

http://jsfiddle.net/UM8ea/

如果我将定位设置为:

h2 { 
   position: absolute; 
   top: 20px; 
   right: -20px; 
}

我得到了想要的结果,但这感觉像是解决方法,而不是解决方案。

【问题讨论】:

    标签: html css


    【解决方案1】:

    很简单。

    查看fiddle

    .outer {
    background: #FFFFFF;
    border-radius: 4px 4px 4px 4px;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
    margin: 0 auto;
    padding:20px 0px;
    position: relative;
    width: 680px;
    text-align: center;
    margin-bottom: 20px;
    }
    

    对于 h2

     h2 
    { 
    position: absolute; 
    top: 5px; 
    right: 20px; 
    margin:0;
    }
    

    【讨论】:

      【解决方案2】:

      您有这种行为是因为.outer 比图像宽,然后.inner 也是。 h2 的位置与.inner 相关,并向右移动。

      如果您将 .outer 设置为 640px 宽度(如图像),您将获得 desired result

      Other solution 是在.inner 上设置margin: 0 20px;

      如果您想要text positioned all top 图像,您可以在这两种情况下设置h2 {margin:0;}

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-15
        • 1970-01-01
        相关资源
        最近更新 更多