tags:

views:

30

answers:

3

I'm creating a div which has to have a close button in the upper right corner just like in the image image

The first image was made in photoshop. I'm trying to do the same but with CSS. "Fechar" is the close button (in Portuguese). What is the better way to properly position it without workarounds, with clean CSS and Web Standards?

Here is my code: http://jsfiddle.net/wZJnd/

This is as far as I could reach.

+1  A: 

You could do a :

img.close {
float:right;
margin:25px 25px 0 0;
}
mike23
with no `position`?
Rodrigo Alves
i'd also float it. <code>position:absolute;</code> would allow the close button to overlap with the content of the box ("Cartao Fidelidada") if it gets too big. The floating button would cause a line break.
opatut
A: 

I would work with div wrappers around the img

So you would have a div for your header "div.header" that would contain these div :

  • div.logo : The logo on the left containing an img tag;
  • div.title : The title of the page;
  • div.close : The close button that would contain your img tag.

I better like using the padding than the margin attribute. I think it works better for compatibility purposes.

Nezrak
+2  A: 

I would use absolute positioning inside a relatively positioned #header:

HTML

<div id="header"> 
  <h1>Your Title</h1>
  <a href="" class="close">Close</a>
</div>

CSS

#header {
    width: 700px;
    height: 200px
    position: relative;

    text-align: center;

    background: #000 url(the-logo.png) no-repeat 30px 10px;
}

#header .close {
    position: absolute;
    top: 20px;
    right: 20px;
}

This will cause the a.close link to use the #header as its coordinate system and position it 20px from the top and right edge.

In my experience padding, margins and float are more sensitive to rendering inconsistency and font size changes than positioning. As a result, I use position whenever possible.

Pat
Perfect! I was searching for this. I knew that I had to use `position relative`, I just didn't know that `.close` would behave like this only when placed inside a **relative positioned div**. BTW, how would you wipe out the line break between the logo and the title? Is it right to use `float: left` in this case?
Rodrigo Alves
The easiest way would be to set your logo as a background image on your `<div class="head">` container. Then if you set your .head as a 100% width, block level element with text-align: center. This will cause your `<h1>` to be in the correct spot and you can use vertical padding on it to space it the correct distance from the top and bottom of the .head container.
Pat