Reputation: 31
i tried everything, but can not center my menu in the center, may anybody help me? it is like in the image img i think the problem is in my css... It just stays to the left. Any ideas? Thank you ahead of time.
body {
background-image: url(2cg3c.jpg);
}
ul {
margin: 0;
padding: 0;
list-style: none;
}
ul li a {
text-decoration: none;
color: white;
display: block;
}
ul li {
float: left;
width: 200px;
height: 40px;
background-color: black;
font-size: 20px;
line-height: 40px;
text-align: center;
opacity: .7;
border: 3px solid #285189;
}
ul li a:hover {
background-color: red;
}
ul li ul li {
display: none;
}
ul li:hover ul li {
display: block
}
<!DOCTYPE html>
<html>
<head>
<title>Sweets</title>
<link rel="stylesheet" type="text/css" href="project1.css" </head>
<body>
<div>
<ul>
<li><a href="#">1</a>
<ul>
<li><a href="#">2</li>
<li><a href="#">3</li>
<li><a href="#">4</li>
<li><a href="#">5</li>
</ul>
</li>
<li><a href="#">6</a>
</li>
<li><a href="#">7</a>
</li>
<li><a href="#">8</a>
</li>
<li><a href="#">9</a>
</li>
</ul>
</div>
</body>
</html>
Upvotes: 1
Views: 5334
Reputation: 101
The easiest fix is set the ul
to be display: inline-block
and set the containing div
to be width: 100%; and text-align: center
.
body {
background-image: url(2cg3c.jpg);
}
.menu-container {
width: 100%;
text-align: center;
}
ul {
margin: 0;
padding: 0;
list-style: none;
display: inline-block;
}
ul li a {
text-decoration: none;
color: white;
display: block;
}
ul li {
float: left;
width: 200px;
height: 40px;
background-color: black;
font-size: 20px;
line-height: 40px;
text-align: center;
opacity: .7;
border: 3px solid #285189;
}
ul li a:hover {
background-color: red;
}
ul li ul li {
display: none;
}
ul li:hover ul li {
display: block
}
<!DOCTYPE html>
<html>
<head>
<title>Sweets</title>
<link rel="stylesheet" type="text/css" href="project1.css" </head>
<body>
<div class="menu-container">
<ul>
<li><a href="#">1</a>
<ul>
<li><a href="#">2</li>
<li><a href="#">3</li>
<li><a href="#">4</li>
<li><a href="#">5</li>
</ul>
</li>
<li><a href="#">6</a>
</li>
<li><a href="#">7</a>
</li>
<li><a href="#">8</a>
</li>
<li><a href="#">9</a>
</li>
</ul>
</div>
</body>
</html>
When you set an element's display to inline-block
, that element will have both qualities of an inline
element and a block
element. In other words it is a block element that can act like html text so properties like text-align: center
will apply to it.
There are 3 other ways to center elements, each good for different situations: http://codepen.io/jzhang300/pen/QdwjMz
1) display: block
and margin: auto
This is good for centering something that has a specified width.
2) flexbox
This is the most comprehensive way to layout elements for most cases. Advantage with this is you can also vertically align elements, not just horizontally.
3) position: absolute
This is good for when you want to center elements with dimensions that exceed container dimensions. It also vertically centers.
Upvotes: 3