block elements widths get set by their content?
Hi i just started trying to teach myself HTML/CSS a few days ago. I really dont like asking for answers id rather figure it out myself. But now i need some help so i can find peace and FINALLY move on. Im trying to make a horizontal menu with one drop down button and links in it.
.container {border:1px solid black;
text-align:left;
border-radius:10px;
overflow:hidden;}
.container a {padding:15px;
display:inline-block;
font-size:30px;
text-decoration:none;
background-color:grey;
color:white;}
.aboutcontainer {display:inline-block;}
.about {position:absolute;
display:none;
width:100%;}
.about a {display:block;
text-align:left;
font-size:20px;
padding:15px 5px;}
.aboutcontainer:hover .about {display:block;}
.container a:hover, .aboutcontainer:hover .button {background-color:red;}
.about a:hover {background-color:lightgrey;}
<div class="container">
<a href="#">Home</a
><a href="#">Media</a
><a href="#">Store</a
><div class="aboutcontainer">
<a class="button" href="#">About</a>
<div class="about">
<a href="#">About2</a>
<a href="#">About3</a>
</div>
</div>
</div>
Yes, an inline-block
element will size to fit it's content.
Why isn't it working in your situation? You have .about
positioned absolute
.
When you position an element absolutely, you are taking it out of the HTML structure, meaning:
Do not leave space for the element. Instead, position it at a specified position relative to its closest positioned ancestor if any, or otherwise relative to the containing block. Absolutely positioned boxes can have margins, and they do not collapse with any other margins.
MDN Docs
This means the element is pulled out of the structure, and no longer influences the surrounding elements, or its parent.
An example of this:
.parent {
background: blue;
}
.child {
background: red;
position: absolute;
top: 20px;
}
Below is the parent element, with a blue background.
<div class="parent">
<div class="child">Bye bye parent</div>
</div>
在这里,我删除了overflow: hidden
从.container
overflow: hidden
并添加position: relative
对于.aboutcontainer
。
.container {
border: 1px solid black;
text-align: left;
border-radius: 10px;
}
.container a {
padding: 15px;
display: inline-block;
font-size: 30px;
text-decoration: none;
background-color: grey;
color: white;
}
.aboutcontainer {
display: inline-block;
position: relative;
}
.about {
position: absolute;
display: none;
width: 100%;
}
.about a {
display: block;
text-align: left;
font-size: 20px;
padding: 15px 5px;
}
.aboutcontainer:hover .about {
display: block;
}
.container a:hover,
.aboutcontainer:hover .button {
background-color: red;
}
.about a:hover {
background-color: lightgrey;
}
<div class="container">
<a href="#">Home</a
><a href="#">Media</a
><a href="#">Store</a
><div class="aboutcontainer">
<a class="button" href="#">About</a>
<div class="about">
<a href="#">About2</a>
<a href="#">About3</a>
</div>
</div>
</div>
链接地址: http://www.djcxy.com/p/81366.html
上一篇: 环绕文字推动图像在它上面时
下一篇: 块元素的宽度由其内容设置?