2017-04-13 42 views
1

以下是我的代码,其中我试图将红色底部应用于div,方式如下:50px左右分别为margin,然后拉伸至最大宽度,但不知何故它正在向左移动。让我知道我该如何让中间出现在div底部,左右两侧留有50px的空间。从中心开始后的伪元素 - CSS

也让我知道为什么::after元素是从中心创建比从最左边。 [参考其创作的图像]。

HTML -

<div class="container"> 
    <h1>This is a simple heading</h1> 
    <h3>This is only a test description</h3> 
</div> 

CSS -

.container { 
    background: #34EACC; 
    width: 100%; 
    text-align: center; 
} 
.container:after { 
    content: ""; 
    position: absolute; 
    width: 100%; 
    margin: 0 50px; 
    height: 1px; 
    background-color: red; 
} 

的jsfiddle - https://jsfiddle.net/gwdvqs5j/

IMAGE -

image-alignment

回答

3

在定义absolute你也应该申报leftright性能,如果想position元素

.container { 
 
    background: #34EACC; 
 
    width: 100%; 
 
    text-align: center; 
 
} 
 

 
.container:after { 
 
    content: ""; 
 
    position: absolute; 
 
    width: 90%; 
 
    left: 0; 
 
    right: 0; 
 
    margin: 0 auto; 
 
    height: 1px; 
 
    background-color: red; 
 
}
<div class="container"> 
 
    <h1>This is a simple heading</h1> 
 
    <h3>This is only a test description</h3> 
 
</div>

2

个使用左,右性能

.container { 
 
    background: #34EACC; 
 
    width: 100%; 
 
    text-align: center; 
 
} 
 
.container:after { 
 
    content: ""; 
 
    position: absolute; 
 
    height: 1px; 
 
    background-color: red; 
 
    left: 50px; 
 
    right: 50px; 
 
}
<div class="container"> 
 
    <h1>This is a simple heading</h1> 
 
    <h3>This is only a test description</h3> 
 
</div>

2

您可以使用转换:转换(),

希望这有助于:)

.container { 
 
    background: #34EACC; 
 
    width: 100%; 
 
    text-align: center; 
 
} 
 
.container:after { 
 
    content: ""; 
 
    position: absolute; 
 
    width: 90%; 
 
    left: 50%; 
 
    transform: translateX(-50%); 
 
    height: 1px; 
 
    background-color: red; 
 
}
<html> 
 
    <head> 
 
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> 
 
    </head> 
 
    <body> 
 
    <div class="container"> 
 
     <h1>This is a simple heading</h1> 
 
     <h3>This is only a test description</h3> 
 
    </div> 
 
    </body> 
 
</html>

+0

我不会推荐这个,因为当它达到了预期的目标,它不是一个非常优雅的解决方案(它纠正了*发生后的问题*,而不是通过正确定义属性来修复根本原因),并且转换已知会导致IE中出现问题(可能不会在这种情况下)。 – tom