CSS - 填充影响 DIV 上的背景图像

标签 css html

我有一个像这样的 div:

<div id="mybox">Hello World</div>

这个的 CSS 是:

#mybox {
    position:absolute;
    left:30px;
    top:147px;
    width:556px;
    height:31px;
    font-family : Verdana, Helvetica, sans-serif;
    font-size : 24px;
    color: white;
        background-image:url('images/image2.jpg');
    background-repeat:no;
    text-align:left;
    vertical-align:middle;
        text-shadow: 0px 0px 10px #000;
}

就像我说的,这个 div 里面有一个文本。在这个例子中:“ Hello World ”。

但我认为文本太靠近左边框,我想在 div 中添加一点填充。所以我添加了这个

padding-left:5px;

问题在于这样做时,div 的图像会向右移动并覆盖右侧的另一个 div。

如何将文本向右移动 5 个像素并保持 div 的图像固定?

谢谢。

最佳答案

你必须使用text-indent

来自 http://reference.sitepoint.com/css/text-indent

margins and padding affect the whole block, text-indent only applies to the first rendered line of text in the element.

你的 css text-indent

#mybox {
    position:absolute;
    left:30px;
    top:147px;
    width:556px;
    height:31px;
    font-family : Verdana, Helvetica, sans-serif;
    font-size : 24px;
    color: white;
        background-image:url('images/image2.jpg');
    background-repeat:no;
    text-align:left;
    vertical-align:middle;
        text-shadow: 0px 0px 10px #000;
    text-indent:100px;
}

检查这个working Demo

重要说明:

来自 http://css-plus.com/2010/09/best-of-css-plus/

If you have a set width of 200px and then add a 20px left padding, the total element size would be 220px. It’s possible to solve this problem by changing the width to 180px, but I find this very annoying as the width has to be changed every time the padding is changed. Text-indent solves this absolutely wonderfully.

关于CSS - 填充影响 DIV 上的背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20957825/

相关文章:

javascript - 让元素在悬停时悬停,添加关闭按钮以便它记住cookie?

html - 使元素均匀地填充给定空间

html - 如何在html中将文字放在图像上?

html - <a> 标签对 <div> 的响应不同

javascript - 需要淡出 div 的帮助

html - 文本字段与标签对齐

css - 如何使用 HTML 和 CSS 创建一个完全灵活的钢琴键盘

html - 即使窗口调整大小,div 也会包装内容

html - 隐藏图像背景

javascript - 通过从用户处获取输入 1 或 2 并单击输入按钮,模型应根据输入进行更改