【问题标题】:CSS magic to center text and img for fixed html用于固定 html 的 CSS 魔法使文本和 img 居中
【发布时间】:2013-05-07 11:31:11
【问题描述】:

我有一段固定的 html,我无法更改它,我想根据自己的喜好设置它的样式,但我不知道怎么做。这就是我所拥有的:

<a title="some title" href="...">
   <img src="....jpg"></img>
   Some text
</a>

CSS:

div.container-outer {
width: 25%;
float:left;
}
div.container-inner {
width: 156px;
margin: 5px;
}
div.container-inner img {
max-width: 156px;
max-height: 124px;
}

我希望文本在 img 下方居中,并且 text 和 img 都以包含 div 的固定宽度居中。图片的宽度和高度未知,但是有一个max-width和一个max-height,并且max-width小于包含的div。此外,图片的底部应位于包含 div 内的固定位置。

我可以随意修改这段代码 sn-p 周围的 html。

这甚至可能吗?在过去的一个小时里,我的头撞到了墙上,我仍然一无所知....

最好的问候, 马库斯

编辑 130513 --------------------------------------------------------- ---

添加了当前的 CSS。这使我的图像左对齐,下面的文本也左对齐。如果图像的高度发生变化,则图像的底部会移动,因为它是顶部对齐的。

【问题讨论】:

  • 发布您的 CSS 或 jsFiddle 链接
  • 你可以先尝试设置 a[title~=some title] img { text-align: center;或边距:0自动;或将它们设置为 display: block; } 你需要告诉我们你从哪里开始。
  • 问题是如果我做 text-align: center 和 img {display:inline} 如果图像宽度很小,文本会跳到图像旁边。

标签: html css image center fixed


【解决方案1】:

到目前为止,我还没有设法在 CSS 中做到这一点……你可以使用 Javascript 吗?

<!DOCTYPE html>
<html>

<head>
    <style>
        div.container-inner {
            width: 156px;
            text-align: center;
            border: 1px solid red;
        }
    </style>
    <script>
        function addBr() {
            document.getElementById('container-inner').innerHTML = document.getElementById('container-inner').innerHTML.replace(/(<img.+?>)/, '$1<br>');
        }
    </script>
</head>

<body onload="addBr();">
    <div id="container-inner" class="container-inner">
        <a title="some title" href="...">
            <img src="images/sample.jpg">
            Some text
        </a>
    </div>
</body>

</html>

演示:http://doug.exploittheweb.com/SO/16521934.html

FWIW,&lt;/img&gt; 不是有效的 HTML,即使在源代码中也几乎肯定不会出现在 .innerHTML 中。

【讨论】:

    【解决方案2】:

    你试过了吗

    <div style="text-align:center">
        <img src="..." alt="..." /><br />
        <span>text<span>
    </div>
    

    您可以在样式参数本身中设置 div 的宽度。您需要在 img 之后添加 BR,因为 img 是内联对象,例如松散文本(文本未包含在 P 元素或其他内容中。

    span 之所以存在只是因为您以后可以对其进行样式化

    【讨论】:

    • 我无法更改 html 块 text,这是我无法访问的代码的 php 输出。我只能在它周围添加html。
    猜你喜欢
    • 1970-01-01
    • 2012-09-30
    • 2021-03-14
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    • 2011-06-24
    相关资源
    最近更新 更多