html - 仅使用 CSS 将图像定位在四个不同的可能位置

标签 html css

我真的很难用语言表达这一点,但我会努力的。我有一个包含一些文本的 div,该文本是动态的,因此它的长度可以根据用户输入而不同。

现在我希望该选项能够将图像放置在以下位置之一,具体取决于选择下拉菜单的值,这将放置图像:

Above the text
Below the text
Left of text
Right of text

我想知道是否有一种简单的方法可以使标记保持不变,即

<img src="">
<span>Text</span>

但使用 CSS 将图像的位置更改为上述任何一个位置。请务必注意,文本宽度和高度是动态的,因此不可能使用精确的像素。

如果可能,我宁愿避免使用 javascript。

最佳答案

这就是你所需要的:

.container {
  display: flex;
}

#p-below:checked ~ .container {
  flex-direction: column-reverse;
}
#p-right:checked ~ .container {
  flex-direction: row-reverse;
}
#p-above:checked ~ .container {
  flex-direction: column;
}

.container {
  display: flex;
}

#p-below:checked ~ .container {
  flex-direction: column-reverse;
}
#p-right:checked ~ .container {
  flex-direction: row-reverse;
}
#p-above:checked ~ .container {
  flex-direction: column;
}


/* everything below is totally optional */

.container {
  justify-content: center;
  align-items: center;
}
.container > .text {
  border: 1px solid #424242;  
  padding: 1rem;
}

.container .image > img {
  display: block;
}
<input name="position" type="radio" checked id="p-above" />
<label for="p-above">Above</label>
<input name="position" type="radio" id="p-below" />
<label for="p-below">Below</label>
<input name="position" type="radio" id="p-left" />
<label for="p-left">Left</label>
<input name="position" type="radio" id="p-right" />
<label for="p-right">Right</label>

<div class="container">
  <div class="image"><img src="http://lorempixel.com/g/400/300" /></div>
  <div class="text">Lorem ipsum dolor sit amet. Have as much text here as you like.</div>
</div>

关于html - 仅使用 CSS 将图像定位在四个不同的可能位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42645967/

相关文章:

html - 全宽嵌入 Vimeo 视频

javascript - 如何从嵌套数组中获取字段值?

html - 使用 "background-position"但我的背景图像正在消失

html - css : display: table (FF works well. 不适用于 Chrome 和 Edge)

javascript - 如何获取 svgElement 的比例?

html - 导航栏 - 差异化

javascript - 如何在 Angular-UI-Router 中的所有命名 View 中更新作用域变量

html - 为什么我的 CSS 类不起作用

php - 在 codeigniter 错误的 View 中加载 css

css - 如何去除使用线性渐变属性时出现的条纹