元素内部具有绝对位置时的CSS边距

时间:2013-02-21 20:01:49

标签: html twitter-bootstrap css

我处境很烦人...... 我认为最好只展示我所做的并告诉你问题是什么,而不是解释一切。

我现在一直在寻找解决方案,但我找不到它。

如果你转到http://jsfiddle.net/bd3Ms/,你会看到一个带有h1标签和内部图像的三个方框。我用CSS修剪了图像(这必须以这种方式完成,无法解决这个问题)。我试图将图像置于框中,但我无法做到这一点。我认为这是因为img元素的绝对定位。

代码:

<html>
<head>
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css" rel="stylesheet">

    <style type="text/css">
        .photo-div {
            overflow:auto;
            height:250px;
            border: 1px solid #000;
        }

        .photo-div-content {
            width:100%;
            margin:0 auto;
        }

        img.clipped {
            position:absolute;
            clip:rect(0px,200px,200px,0px);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row">
            <div id="div-1" class="photo-div span4">
                <div class="photo-div-content">
                    <h1>Logitech Mouse</h1>
                    <img class="clipped" src="https://www.google.nl/images/srpr/logo3w.png">
                </div>
            </div>
                <div id="div-2" class="photo-div span4">
                <div class="photo-div-content">
                    <h1>Logitech Mouse</h1>
                    <img class="clipped" src="https://www.google.nl/images/srpr/logo3w.png">
                </div>
            </div>
            <div id="div-3" class="photo-div span4">
                <div class="photo-div-content">
                    <h1>Logitech Mouse</h1>
                    <img class="clipped" src="https://www.google.nl/images/srpr/logo3w.png">
                </div>
            </div>
        </div>
    </div>
</body>

我正在使用Twitter Bootstrap,我正在构建的网站将完全响应,所以只是添加一个边距 - 对我来说不起作用..

我希望我能说清楚问题是什么。

提前感谢您的帮助!

4 个答案:

答案 0 :(得分:1)

如何不剪切和居中图像呢?

img.clipped {
    background:url(https://www.google.nl/images/srpr/logo3w.png) center center no-repeat;
}

直播示例: http://jsfiddle.net/bd3Ms/1/

此处有更多替代方案:

答案 1 :(得分:1)

如果我正确理解您的问题,您希望将文本和剪裁图像都居中。看看这是否有帮助:http://jsfiddle.net/panchroma/7Lq6B/

重要的一点是,我将图像包裹在一个居中的div中,该div与裁剪尺寸相同。

CSS

.img-wrap{ /* dimensions should match clipping size */
width:200px;
height:200px;
margin:0 auto;
}

<强> HTML

<div id="div-2" class="photo-div span4">
<div class="photo-div-content">
<h1>Logitech Mouse</h1>
<div class="img-wrap">
<img class="clipped" src="https://www.google.nl/images/srpr/logo3w.png"></div>
</div>
</div>
祝你好运!

答案 2 :(得分:1)

由于图像绝对定位,您可以选择更多选项。试试这个:

img.clipped {
    position: absolute;
    left: 50%;
    margin-left: -25%;
    clip:rect(0px,200px,200px,0px);
}

它不是漂亮的代码,但它位于父div的中间。

答案 3 :(得分:1)

我用与CSS精灵相同的技术做到了。

.photo-div-content{
    background: 'url('IMG URL') repeat scroll -0px -0px transparent');
    height: 200px;
    width: 200px;
    margin: 0 auto;
}

目前我认为这是实现目标的最佳方式:使用CSS在div中间显示图像的一部分。