使图像显示在div

时间:2018-04-01 05:08:00

标签: html css

我正在尝试制作下面的图片。

蓝色方框是div,红色方块是中心对齐的图像。图像与div的边框重叠,但位于div中的文本下方。 image of intended outcome

我该怎么做?

2 个答案:

答案 0 :(得分:2)

解释

重叠

z-index 如果您需要不同层中的div,那就太好了 z-index较小的div将保持在后面,因此您可以标记边框 (虽然我认为在这种情况下没有必要)

中心对齐

要对齐中间的图像,请将自动边距添加到图像。

图像位置

如果您希望30%的图像位于边框内,将图像的顶部移动高度的-70%。因此,如果图像的高度为100px,请设置顶部:-70px;

文字位置

由于原始图片覆盖了文字上方的空白区域,因此您必须向上移动文字以覆盖空白区域。为此,请将文本顶部移动到图像的高度。因此,在这种情况下,设置顶部:-100px; 向上移动文本后,空间将显示在分隔的底部。因此,要缩小边框,您需要设置 margin-bottom:-100px; 这将缩小div以删除

所占用的空白

整个分区位置

因为您将图像移动到整个div上方70px,您需要设置 margin-top:70px; 以将整个div向下移动以防止它被裁剪掉。

.border-div{
                border: 3px solid blue;
                margin-top: 70px;
                z-index: -1;
            }
            .redsquare{
                height: 100px;
                width: 100px;
                background-color: red;
                z-index: 0;
                margin: 0 auto;
                position: relative;
                top: -50px;
            }
            .text{
                position: relative;
                top: -100px;
                z-index: 1;
                margin-bottom: -100px;
            }
 <div class="border-div">
            <div class="redsquare"></div>
            <div class="text">Lorem ipsum has become the industry standard for design mockups and prototypes. By adding a little bit of Latin to a mockup, you’re able to show clients a more complete version of your design without actually having to invest time and effort drafting copy.

But despite all its benefits, seeing the same random Latin text in every design can get a little boring for you and your clients. So if you have a client who’s got a sense of humour or if you’re just tired of going the traditional route in your mockups, here are 15 creative and funny lorem ipsum text generators that are sure to lighten the mood at any client meeting.
        </div>

答案 1 :(得分:0)

我最好的建议是在儿童中使用绝对位置,并在边框中使用相对位置,然后为儿童设置位置。有点像:https://jsfiddle.net/c39xej68/4/

.redsqr {
  background-color: red;
  height: 50px;
  width: 50px;
  position: absolute;
  top: -30px;
  margin: auto;
}

.bounder {
  position: relative;
}

.text {
  border: 1px solid blue;
}