Arun
Arun

Reputation: 3077

Padding in combination with :before in CSS

Here's my HTML

<div class="a" style="height: 100px; background: red; padding-top: 40px">
</div>
<br/>
<br/>
<div class="b" style="height: 100px; background: red; padding-top: 40px">
</div>

and my css

.a:before { background-color: green; height:10px;display: block; content: " "; }
.b { border-top: solid 10px green; }

and here's the fiddle

http://jsfiddle.net/LZgYP/

I want the first div tag to look like the second.

I want to use :before to add border (instead of border-top) to the div tag because I'll be using patterns (images) later. But I want the padding after the border, not before. Is there a way?

I'm building a generic SCSS library to specify the top border. Users can select a solid border or a pattern - I'll have a library of patterns too. In case of pattern I guess the only option is to use :before and specify a background image with repeat-x. Therefore I want to remain consistent and use :before to specify the border and I want this border to stick to the top even if the actual tag has padding specified.

And since this is generic, I will not know what padding the tag has, so negative margins on the :before css can't be used

Upvotes: 2

Views: 1151

Answers (2)

Aurelio
Aurelio

Reputation: 25822

I must confess that I can't understand why you don't want to go with a simple border, still here's what I'd do to mimick a border-top. I'd place a :before pseudo-element absolutely positioned to the top. Only prerequisite is to relative position the main div so the pseudo element can be placed on top.

.a:before { 
    background-color: green; 
    height:10px; 
    content: ""; 
    width: 100%;
    position: absolute; 
    top: 0;}

Here's a fiddle, hope it solves the issue, http://jsfiddle.net/gleezer/ZVUFv/1/

Upvotes: 0

osyan
osyan

Reputation: 1866

Answer UPDATED:
add padding-bottom to the a:before and remove padding-top from DIV a

<div class="x" style="height: 100px; background: red;">
    blah blah
</div>
<br/>
<br/>
<div class="y" style="height: 100px; background: red;">
    blah blah
</div> 

and

.a:before { background-color: green; height:10px;display: block; content: " ";padding-bottom:40px }
.b:before { background-color: green; height:10px;display: block; content: " ";margin-bottom:40px }

see this jsfiddle

Upvotes: 2

Related Questions