HTML内联图像容器大小为position:relative

时间:2018-01-24 07:34:04

标签: html css image css3

通常情况下,当内联元素中有图像时 - 例如,span展开以适合图像,不是吗? 我试图在图像上放置绝对div - 很简单。 当图像大小是动态的时,问题就开始了,并且没有固定大小。

我尝试避免使用Javascript。它必须适合所有浏览器

JS FIDDLE

HTML和CSS:



body {
  background-color: red;
  width: 100%;
  height: 100%;
}

.realContainer {
  background-color: #efefef;
  height: 100%;
  width: 100%;
  position: relative;
}

.realContainer .inlineContainer {
  position: relative;
}

.realContainer * {
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
}

.absoluteDiv {
  position: absolute;
  top: 50%;
  left: 50%;
  background-color: green;
}

<button onclick="changeSize()">changeSize</button>

<div class="bigContainer">
  <div class="realContainer">
    <span class="inlineContainer">
            <img src="https://openclipart.org/download/216413/coniglio_rabbit_small.svg" />
            <div class="absoluteDiv">
              XXX
            </div>
          </span>
  </div>
</div>
&#13;
&#13;
&#13;

我试图让XXX(绝对div)始终保持最高50%并保留50%的图像。并且图像必须适合容器而不能拉伸或切割。

1 个答案:

答案 0 :(得分:0)

请注意:

top: 50%;
left: 50%;

而不是(在你的JSFiddle中):

top: -50%;
left: 50%;

我试着做你所描述的,请试一试 基本上我改变了删除位置:相对于inlineContainer,以确保你的absoluteDiv绝对是realContainer:

&#13;
&#13;
body{
    background-color:red;
    width:100%;
    height:100%;
}


.realContainer{
    background-color:#efefef;
    height:100%;
    width:100%;
    position:relative;
}

.realContainer .inlineContainer{
}

.realContainer *{
    max-width:100%;
    max-height:100%;
    width: auto;
    height: auto;
}


.absoluteDiv{
    position:absolute;
    top:50%;
    left:50%;
    background-color:green;
    transition: translate(-50%, -50%);
}
&#13;
<button onclick="changeSize()">changeSize</button>

<div class="bigContainer">
  <div class="realContainer">
    <span class="inlineContainer">
        <img src="https://openclipart.org/download/216413/coniglio_rabbit_small.svg" />
        <div class="absoluteDiv">XXX</div>
    </span>
  </div>
</div>
&#13;
&#13;
&#13;

另一种选择是更改inlineContainer以显示:inline-block

&#13;
&#13;
body{
    background-color:red;
    width:100%;
    height:100%;
}


.realContainer{
    background-color:#efefef;
    height:100%;
    width:100%;
    position:relative;
}

.realContainer .inlineContainer{
    display: inline-block;
    position: relative;
}

.realContainer *{
    max-width:100%;
    max-height:100%;
    width: auto;
    height: auto;
}


.absoluteDiv{
    position:absolute;
    top:50%;
    left:50%;
    background-color:green;
    transition: translate(-50%, -50%);
}
&#13;
<button onclick="changeSize()">changeSize</button>

<div class="bigContainer">
  <div class="realContainer">
    <span class="inlineContainer">
        <img src="https://openclipart.org/download/216413/coniglio_rabbit_small.svg" />
        <div class="absoluteDiv">XXX</div>
    </span>
  </div>
</div>
&#13;
&#13;
&#13;