6

我想从屏幕左侧到居中的div. 以div为中心margin: auto;

此图像显示了它的外观:

例子

4

4 回答 4

7

这是使用calc的示例:

.box{
    width:200px;
    height:200px;
    border:1px solid blue;
    margin:0 auto;
}

.line{
    border: 1px solid red;
    width: calc(((100% - 200px)/2) + 200px);
}

JSFiddle

浏览器支持

于 2013-07-29T06:15:40.243 回答
5

这个解决方案怎么样?不需要额外的标记,跨浏览器并且不依赖于元素的宽度

#content {
    width:400px;
    height: 200px;
    margin:auto;
    position: relative;
}

#content:before{
    content: '';
    height: 1px;
    background: red;
    position: absolute;
    top: -5px;
    right: 0;
    width: 999%; /*a large number*/
}

演示小提琴

于 2013-07-29T06:48:46.737 回答
3

这是另一个解决方案,它是跨浏览器http://jsfiddle.net/9qrSy/3

<div class="inner"></div>
<div class="wrapp"></div>

css 



   body {
    padding:8px;
}
div.wrapp {
    width:300px;
    height:300px;
    border:2px solid green;
    margin:auto;
    position:relative;
}
div.wrapp:before {
    content:'';
    position:absolute;
    width:100%;
    height:1px;
    right:0;
    top:-6px;
    background:blue;
    z-index:1;

}
.inner {
    width:50%;
    float:left;
    position:absolute;
    height:1px;
    left:0;
    top:12px;
     background:blue;


}
于 2013-07-29T06:25:35.683 回答
0

我不确定这是否适用于所有浏览器,但我相信hr会占用您提供的所有空间。因此,您可以给它一个较大的负左边距并将其放在居中的 div 内。除了 hr 元素,您也可以使用空的 div,这可能更容易使用,也可能不会更容易使用。您可以border-top将该 div 的样式设置为更广泛的边框类型(例如,点状)。

<div id="content">
    <hr id="bar" />
    <div id="realcontent">    
        Something here
    </div>
</div>

使用 CSS:

#content {
    width: 400px;
    margin: auto;
    color: white;
}

#bar {
    margin-left: -1000px;
    margin-bottom: 5px;
    background: blue;
}

#realcontent {
    background-color: #000000;
}
于 2013-07-29T06:36:29.207 回答