please take a look at JSFiddle example.
I want to make menu with closing ‘x’ on it’s right side. Menu pops-up after click on green div.
HTML
<div class="field">
<nav id="menu">
<ul>
<li>Menu item 1</li>
<li>Menu item 2</li>
<li>Item 3</li>
</ul>
<div class="close">X</div>
</nav>
CSS
.field {
background: green;
width: 350px;
height: 200px;
margin: 10px auto;
position: relative;
cursor: pointer;
}
#menu {
position: absolute;
display: none;
}
#menu ul {
width: 80%;
border: 1px solid #999;
float: left;
}
#menu li {
background: #fff;
padding: 5% 15%;
border-width: 0 0 1px 0;
border-style: solid;
border-color: #999;
white-space: nowrap;
}
#menu .close {
background: #ccc;
width: 20%;
padding: 5%;
float: right;
}
JS
(JS is messy, I wrote it on quickly)
$('.field').on('click', function (e) {
var $pointer = $('#pointer'),
$menu = $('#menu'),
parentOffset = $(this).offset(),
relX = e.pageX - parentOffset.left,
relY = e.pageY - parentOffset.top,
circleX = relX - ($pointer.outerWidth() / 2) + 1,
circleY = relY - ($pointer.outerHeight() / 2) + 1;
$pointer.css('left', circleX);
$pointer.css('top', circleY);
$pointer.show();
$menu.css('left', circleX + $pointer.outerWidth());
$menu.css('top', circleY);
$menu.show();
$menu.one('click', '.close', function (e) {
$menu.hide();
$pointer.hide();
e.stopPropagation();
});
});
There are 2 issues:
-
li items doesn’t overflow properly text inside them;
-
[x] element is under menu and not on its right side;
I tried different combinations suggested in other, similar questions but nothing works or I’m to tired and I missed something.
Important thing is that there should not be any hard coded values. Properly values are only %. That’s because it should look good on different borwser sizes.
Any ideas how to fix those issues?
You should take a look at the CSS Box model. Padding, border and margin are always added to the width/height of the element and are not included in the width you define. Your floating X is jumping down, because there are no more 20% space left on the right side of the
ul.Better place the X outside of your div. You can also leave out all the floats. Set
position: absoluteon div.close and move it outside the boundary of the container usingleft: 100%.By the way,
white-space: nowrapleads to your menu elements’ texts being out of the boundary of theli, which is not very flexible.