Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make adjacent sibling elements same width using only CSS

I'm sorry in advance because I cannot show the code/images of what I'm working on due to confidentiality reasons, however I think I can explain it quite simply.

I have an <h1> element that acts as the title to my webpage - this title can change in length based on the title of the specific page the user is on, so it could say "Homepage" or it could say "Saved Projects", etc. The length varies.

The <h1> has a sibling element, a <ul>, that acts as a dropdown to navigate to these other pages.

My goal is to make the size of the dropdown be the same size as the <h1> at all times. Currently the width is explicit, I've tried 'auto' which did not work, naturally and am looking for other workarounds now but I figured I could post here in the meantime.

I am using LESS, so I know variables are big and it could be a matter of passing a variable as the value for the dropdown width, however I don't know if these variables can be dynamic based on the length of the <h1>. I am new to LESS.

I've browsed a couple other posts asking a similar questions, but none have gotten a very solid solution. Google also wasn't too helpful, most articles talked about parent-child sizes or keeping width/height relative. Not comparing widths of siblings.

Thanks for any assistance!

like image 433
alex.mo.07 Avatar asked Oct 20 '22 03:10

alex.mo.07


1 Answers

I tried to make a demo based on your description (without revealing the cure to cancer). Not sure if I understood you correctly, but is this what you are after? http://jsbin.com/hekimije/1/edit (jsFiddle is down :-( )

If so, allow me to explain, as it is in fact quite simple:

  • add a wrapper around your h1 and ul
    • float it left to make it take the width of its content
    • give it a position relative so you can use it to position your ul against
  • position the ul absolute
    • give it a left and right of 0 to make it take the same width as its parent
    • give it a top of 100% to start at the bottom edge of its parent

This method does lift your ul out of the document flow, but for a dropdown that is usually desirable, so it shouldn't be an issue.

And the full code:

HTML

  <div id='title-wrapper'>
    <h1>Some title</h1>
    <ul>
      <li>item 1</li>
      <li>item 2</li>
    </ul> 
  </div>

Less

#title-wrapper {
  float: left; 
  position: relative;

  ul {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0; 
  }
}

All the rest of the code in the jsBin is just to make things a bit better visible. You can change the length of the title and you'll notice the ul follows. Obviously you have to hover the title to see the ul, it is a dropdown after all...

like image 142
Pevara Avatar answered Oct 24 '22 12:10

Pevara