[英]Positioning a heading relative to (above) an absolute div
我有一个块<div>
我想通过position: absolute
来定义精确的像素坐标,但是我想将标题放置在其父<div>
上方。 如果字体大小发生更改(或用户放大了文本),则<div>
块必须保留在完全相同的位置,但是标题可以向上/向下移动以容纳较大/较小的文本。
老实说,这里没有一些示例代码,但是可能有助于说明问题。 这只是我尝试过的变体之一:
<!doctype html>
<html>
<head>
<title>Positioning Test</title>
<style>
#box1 { border: red 1px solid; }
#box1 h4 { margin: 0; color: blue }
.inner_box {
background: #aaf;
width: 400px;
height: 50px;
}
.target_pos {
position: absolute;
top: 50px;
left: 100px;
}
#marker {
width: 10px;
height: 10px;
background: red;
}
</style>
</head>
<body>
<div id="box1">
<h4>Heading</h4>
<div class="inner_box target_pos">
This is the <strong>inner_box</strong>.
</div>
</div>
<!-- Marks where the inner_box should begin -->
<div id="marker" class="target_pos"></div>
</body>
</html>
这个想法是,蓝色的inner_box
必须正好位于marker
(即marker
),但“ Heading
文本必须直接位于marker
正上方,红色的1px边框应将所有内容括起来。
这是在Firefox中的外观:
这是我希望它看起来的样子:
由于我有几个要使用的框,并且它们的位置可能会根据视口的大小而变化,并且标题字体/文本也会有所不同,因此在这里我需要一个动态解决方案。 我更喜欢纯CSS3,但是如果需要JS,我可以接受。
我为您创建了一个小提琴,该小提琴适用于任何字体大小,位置和盒子数。
http://jsfiddle.net/y73sqdr9/3/
也
的HTML
<div class="box target">
<h1>Headingggggggggg</h1>
<div class="inner">
This is the <strong>inner_box</strong>.
</div>
</div>
<div class="square target"></div>
<div class="box target2">
<h1>Headingggggggggg</h1>
<div class="inner">
This is the <strong>inner_box</strong>.
</div>
</div>
<div class="square target2"></div>
的CSS
.box {
position: absolute;
border: 1px solid red;
border-top: none; }
.box h1 {
margin: -2em -1px -1px;
padding: .5em;
border: 1px solid red;
border-bottom: none;
line-height: 1; }
.box .inner {
padding: 1em;
background: #CCF; }
.square {
position: absolute;
width: 16px;
height: 16px;
background: red; }
.target { left: 100px; top: 150px; }
.target2 { left: 120px; top: 280px; }
希望对您有所帮助!
如何完成的:
位置ID给出了整个元素的位置。
box类定义了框的宽度和高度,并且只在左下和右下都有边框,使顶部保持打开状态,因为标题将在那里
标题类的高度设置为零,以不影响框的位置,并向上移动18 px
h4在左上方和右上方有边框,但在底部没有边框,因此不会遮挡盒子
的HTML:
<!DOCTYPE html>
<html>
<head>
<title>Positioning Test</title>
<style>
.header{
position: relative;
bottom: 18px;
right:1px;
background: white;
height:0px;
}
.header h4{
width: 400px;
margin:0;
padding:0;
border: 1px red solid;
border-bottom:none;
}
.box{
border: 1px red solid;
border-top:none;
width: 400px;
height: 300px;
background: #aaf;
}
#position1 {
position: absolute;
top: 50px;
left: 100px;
}
</style>
</head>
<body>
<div id="position1" class="box">
<div class="header">
<h4>Title</h4>
</div>
<div class="inner">
I'm inside!
</div>
</div>
</body>
<html>
首先,您的身体标签没有包装您的代码。
其次,您的红色框div应该包装所有其他div并最后关闭。 早点关门
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.