user3144851
user3144851

Reputation: 39

Drawing a Square with width:50% in CSS?

I would like to display a square on a "mobile" WebApp. The width should be half of the screen size. On any screen. How to declare the height?

#square{
    position:absolute;
    background:black;
    width:50%;  
}

And how would I center such elements, with no fixed size?

thank you very much.

Upvotes: 1

Views: 1076

Answers (2)

curiouscrab
curiouscrab

Reputation: 3

I'm guessing you mean height:50% or how much of the screen you want to cover. Then, you put left:25%; top:25%; position:absolute; and it should be centered. You may want to change absolute to fixed in the event that you want to the square to never move. You end with .box {background-color:#000000; /*makes box black*/ height:50%/*change to 100% if want square on computer screen*/; width:50%; /*makes your box*/ left:25%; top:25%/*change this when you change height of box*/; position:absolute; /*positions your box*/} and your HTML would be:
<html>
<head>
<style>
.box {background-color:#000000; /*makes box black*/ height:50%/*change to 100% if want square on computer screen*/; width:50%; /*makes your box*/ left:25%; top:25%/*change this when you change height of box*/; position:absolute; /*positions your box*/}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>

Upvotes: 0

j08691
j08691

Reputation: 207901

You should be able to do something along these lines:

.sq{
    padding-bottom: 50%;
    width: 50%;
    height: 0;
    background: red;
    margin:0 auto;
}

jsFiddle example

To center vertically and horizontally, try:

.sq{
    width: 50%;
    height: 0;
    padding-bottom: 50%;
    background: red;
    position:absolute;
    margin:auto;
    top:0;
    bottom:0;
    left:0;
    right:0;
}

jsFiddle example

Upvotes: 2

Related Questions