简体   繁体   中英

Adapt div containing elements to different resolutions

I have a div which is a bar that should always stay at the top of the screen. It displays the score and how many lives you have (each one is a canvas). I need the score and the lives to always be in the same position despite of different screen resolutions.

HTML:

<div class='upperbar'>
<h1 id="scoreword">SCORE: number</h1>
<div class="lives">
    <canvas id="life1"  width="100" height="100"></canvas>
    <canvas id="life2"  width="100" height="100"></canvas>
    <canvas id="life3"  width="100" height="100"></canvas>
</div>
</div>

CSS:

.upperbar {
display: flex;
height: 8.5%;
width: 100%;
background: rgba(0, 0, 0, .2);
}

#scoreword {
position: absolute;
opacity: 1;
font-size: 1.8em;
text-align: left;
position: relative;
top: 50%;
left: 2%;
}

.lives {
position: relative;
right: 0;
}

I'm quite confused about this. How can I do it?

You are using display:flex in your wrapper div, but you aren't applying any flex rules in your child divs.

Check out my changes to your css here: http://jsfiddle.net/7ns1epa5/

.upperbar {
display: flex;
height: 8.5%;
width: 100%;
background: rgba(0, 0, 0, .2);
}

#scoreword {
opacity: 1;
font-size: 1.8em;
text-align: left;
top: 50%;
    background-color:orange;
    flex:1;
}

.lives {
    background-color:red;
    flex:1;
}

flex:1 on both child divs says "use 50% of the parent flex wrapper". The math behind it is, "add up the total flex of each child div as the denominator, then take their flex number as the numerator" -- so two child divs with flex:1 would be 1+1=2, each div would be 1/2 or 50%" If you changed one of the child divs to flex:2, it would be 1+2=3 and the divs would be 1/3 and 2/3.

same idea with flex and justify-content:space-between;

http://jsfiddle.net/bestiole/tjg09mbt/

.upperbar {
    display: flex;
    justify-content:space-between;
    height: 8.5%;
    width: 100%;
    background: rgba(0, 0, 0, .2);
}

#scoreword {
    font-size: 1.8em;
    margin:0;
    background:#f00;
}

.lives {
    background:#ff0;
}

your code is lacking a closing div

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM