CSS 定位 - 顶部和右侧
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3389925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSS Positioning - Top and Right
提问by Rodrigo Souza
I'm creating a div which has to have a close button in the upper right corner just like in the image image http://rookery9.aviary.com.s3.amazonaws.com/4655000/4655386_f01b_150x250.jpg
我正在创建一个 div,它必须在右上角有一个关闭按钮,就像 图像 http://rookery9.aviary.com.s3.amazonaws.com/4655000/4655386_f01b_150x250.jpg
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?
第一张图片是用photoshop制作的。我正在尝试使用 CSS 做同样的事情。“Fechar”是关闭按钮(葡萄牙语)。使用干净的 CSS 和 Web 标准,在没有变通方法的情况下正确定位它的更好方法是什么?
Here is my code: http://jsfiddle.net/wZJnd/
这是我的代码:http: //jsfiddle.net/wZJnd/
This is as far as I could reach.
这是我所能达到的。
回答by Pat
I would use absolute positioning inside a relatively positioned #header:
我会在相对定位的#header 中使用绝对定位:
HTML
HTML
<div id="header">
<h1>Your Title</h1>
<a href="" class="close">Close</a>
</div>
CSS
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.
这将导致a.close
链接使用 #header 作为其坐标系,并将其放置在距离顶部和右侧边缘 20 像素的位置。
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.
根据我的经验,填充、边距和浮动比定位对渲染不一致和字体大小变化更敏感。因此,我尽可能使用位置。
回答by mike23
You could do a :
你可以做一个:
img.close {
float:right;
margin:25px 25px 0 0;
}
回答by mike23
I would work with div wrappers around the img
我会在 img 周围使用 div 包装器
So you would have a div for your header "div.header" that would contain these div :
所以你的标题“div.header”会有一个包含这些 div 的 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.
- div.logo : 左边的 logo 包含一个 img 标签;
- div.title : 页面标题;
- div.close :将包含您的 img 标签的关闭按钮。
I better like using the padding than the margin attribute. I think it works better for compatibility purposes.
我更喜欢使用填充而不是边距属性。我认为它在兼容性方面效果更好。