Element Size Based on Monitor Width

2020-04-18 05:45发布

问题:

I am creating my own personal website as a test for what I have learned so far in HTML and JavaScript. I made the toolbar, and it looks nice on my monitor, which has quite a large width. I have the toolbar contents to be in the center. I tried accessing it on a smaller monitor, and the elements in the toolbar overlapped each other because I set the contents based on percentages. I know that measuring with pixels will come up with the same problem. How would I create a website where if the monitor width is larger than x pixels, then it will center the contents of the toolbar, but if the monitor width is smaller than x pixels, it will not center the contents of the toolbar?

As you can see in this jsFiddle, the elements overlap, but if you drag the view pane wider, you can see that it centers.

index.html:

<body>
<div id="header">
    <div id="toolbar">
        <div id="links">
            <ol>
                <li id="home"><a href="justinpchang.zxq.net/index.html">Home</a></li>
                <li id="blog"><a href="justinpchang.zxq.net/blog/index.html">Blog</a></li>
                <li id="forum"><a href="justinpchang.zxq.net/forum/index.html">Forums</a></li>
                <li id="chatbox"><a href="justinpchang.zxq.net/chatbox/index.html">Chatbox</a></li>
                <li id="code"><a href="justinpchang.zxq.net/code/index.html">Code</a></li>
                <li id="calendar"><a href="justinpchang.zxq.net/calendar/index.html">Calendar</a></li>
            </ol>
        </div>
        <div id="login">
            Username: <input type="text" name="firstname"></input>
            Password: <input type="text" name="lastname"></input>
            <a href="justinpchang.zxq.net/user/loginlanding.html"><button id="submit" class="button">Submit</button></a>
        </div>
    </div>
</div>

CSS:

body{
background-color:#EBF2F0;
margin-top:50px;
}
#links{
padding:0px;
margin:0px;
top:-10px;
position:absolute;
vertical-align: center;
}
a:link{
text-decoration:none;
color:#FFFF00;
}
a:visited{
text-decoration:none;
color:#FFFF00;
}
a:hover{
text-decoration:none;
color:#000BF2;
}
a:active{
text-decoration:none;
color:#FFFF00;
}
li{
display:inline;
padding:0px;
font-family:Courier;
}
ol{
list-style-type: none;
}
#header{
width:100%;
padding:5px 10px;
margin:0px;
height:25px;
top:0px;
left:0px;
position:fixed;
background-color:#000000;   
}
#toolbar{
width:70%;
margin-left:15%;
margin-right:15%;
}
#home,#blog,#forum,#chatbox,#code,#calendar{
padding:10px;
color:#000BF2;
}
#home:hover,#blog:hover,#forum:hover,#chatbox:hover,#code:hover,#calendar:hover{
background-color:#2E2E2D;
color:#000BF2;
}
#login{
color:#FFFFFF;
margin-right:30px;
text-align:right;
}
#submit{
margin-top:-7px;
margin-left:10px;
padding:6px;
}

回答1:

If you need a CSS only solution you could play with min-width:

#toolbar{
  width:70%;
  margin-left:15%;
  margin-right:15%;
  min-width:1200px;
}

Fiddle



标签: html css width