【问题标题】:How to float an img left of text when the text is before it in the markup?当文本在标记中之前,如何在文本左侧浮动 img?
【发布时间】:2015-09-17 07:48:53
【问题描述】:

我什至不知道这是否可能。我正在尝试使图像向左浮动到文本(或向右浮动到图像)。我需要内容位于图像上方,就像 CSS 查询一样,对于移动设备,我想删除格式并将文本保留在图像上方。

https://jsfiddle.net/as1wj9sp/

我尝试了固定定位,但图像不符合布局的其余部分。

* {
	padding: 0px;
	margin: 0px;
	list-style-type: none;
	font: 1em/1em Arial, Tahoma, Helvetica, sans-serif;
}
#content {
	margin: auto;
	background: #FCC;
	padding: 10px;
}
#index {
	background: #063;
	padding: 2px;
	overflow: hidden;
}
#index h1 {
	float: right;
}
#index img {
	display: block;
	float: left;
	max-width: 90%;
}
<div id="content">
    <div id="index"><h1>The Right Ingredients At The Real Dose asdadasda ad ad as dasdas as das das das dasdas dd asd asdsadasdasd asdasdasd asdasdasd asdasdas dad asd as</h1>
    <img src="img/image.jpg" alt="test" width="200" height="200" /></div>
</div>

【问题讨论】:

  • 目前尚不清楚这里的实际问题是什么。为什么图像需要浮动?你在使用媒体查询吗?
  • 我稍后会使用查询,但是对于这个网络版本,我想将图像向左浮动,文本向右浮动。不,它不必浮动,我只是不知道该怎么做。当我更改移动查询并删除将文本留在图像上方而不是下方的格式时,我只想要一种简单的方法。

标签: css image css-float


【解决方案1】:

我会将两个元素都更改为 display: block,然后您可能需要元素的 宽度,为简单起见,每个元素的宽度为 50%。

使用移动设备的@media-query 来完成这个概念。

类似这样的:

    #index h1 {
        float: right;
        display: block;
        width: 60%;
    }
    #index img {
        display: block;
        float: left;
        width: 40%;
    }

/* Or whatever max-width you want */
    @media (max-width: 768px) {
        #index h1,
        #index img {
            float: left;
            width: auto;
        }
    }

【讨论】:

  • 天哪,为什么我没有意识到为这两个元素设置宽度。谢谢人。这似乎也与浏览器兼容。
【解决方案2】:

这个答案不使用浮点数,但是它确实实现了你想要做的事情。如果您不需要支持旧浏览器,可以使用display: flex;order。它适用于所有现代浏览器。

JSFiddle Example

* {
    padding: 0px;
    margin: 0px;
    list-style-type: none;
    font: 1em/1em Arial, Tahoma, Helvetica, sans-serif;
}
#content {
    margin: auto;
    background: #FCC;
    padding: 10px;
}
#index {
    background: #063;
    padding: 2px;
    overflow: hidden;
    display: flex;
    display: -webkit-flex;
}
#index h1 {
    order: 2;
    -webkit-order: 2;
}
#index img {
    display: block;
    max-width: 90%;
    order: 1;
    -webkit-order: 1;
}
<div id="content">
    <div id="index">
        <h1>The Right Ingredients At The Real Dose asdadasda ad ad as dasdas as das das das dasdas dd asd asdsadasdasd asdasdasd asdasdasd asdasdas dad asd as</h1>
        <img src="img/image.jpg" alt="test" width="200" height="200" />
    </div>
</div>

-webkit- 前缀用于 Safari。

【讨论】:

  • 泰勒,谢谢,这看起来很棒。我现在并没有真正研究旧浏览器,也许以后会根据用户浏览器进行调整。这正是我所需要的。
猜你喜欢
  • 2023-03-30
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
  • 1970-01-01
  • 2014-12-04
  • 2019-10-30
相关资源
最近更新 更多