Skip to content Skip to sidebar Skip to footer

How To Select Margin For A Background Image In Css/css3?

I am not sure why setting width and height to 70% didn't work. Is there anyway, to fix this so we can have margin on all 4 sides of the image? Like I want to have 30% of the page f

Solution 1:

You could use the flex properie and background-size: DEMO

html {
    height:100%;/* size that body can inherit or use as reference */width:100%;/* size that body can inherit or use as reference */background:black;/* background needs to set and be different from body, else it is drawn here */display:flex;/* the magic that everybody will love */
}
body {
    margin:auto;/* within a flex container it applys on both axis */background-image:url('https://uwmadison.qualtrics.com/CP/Graphic.php?IM=IM_00pfOKSXTudGqfb');
    background-repeat: no-repeat;
    background-size:70vw70vh;/* if you use flex, you may use vx units too :) */
}

Or display:table/table-cell properties and background-size: DEMO

html {
    height:100%;
    width:100%;
    background:black;
    display:table;
}
body {
    display:table-cell;
    background-image:url('https://uwmadison.qualtrics.com/CP/Graphic.php?IM=IM_00pfOKSXTudGqfb');
    background-repeat: no-repeat;
    background-position:center;
    background-size:70%70%;
}

Solution 2:

You may not be able to do it with CSS alone. Here is a fiddle accomplishing what I think you're after. You can use 4 empty divs and style them with CSS fixing their position on the page in the appropriate locations:

http://jsfiddle.net/stacigh/A5J6J/

The HTML:

<divclass="border-top"></div><divclass="border-right"></div><divclass="border-bottom"></div><divclass="border-left"></div>

The CSS:

* {
  margin: 0;
  padding: 0;
}
body {
  background-image:url('http://placekitten.com/g/1024/768');
  background-repeat: no-repeat;
}
.border-top, .border-right, .border-bottom, .border-left {
  position: fixed;
  background-color: white;
   z-index: 3;
}
.border-top, .border-bottom {
  width: 100%;
  height: 30%;
}
.border-right, .border-left {
  height: 100%;
  width: 30%;
}
.border-top {
  top: 0;
}
.border-bottom {
  bottom: 0;
}
.border-right {
  right: 0;
}
.border-left {
  left: 0;
}

Of course, if you only want to center the image in the window, you could use this:

body {
  background-image: url('path/to/image.png');
  background-position: center;
}

Solution 3:

Another alternative:

html, body {
    min-height: 100%;
}

body {
    background-image:url('https://uwmadison.qualtrics.com/CP/Graphic.php?IM=IM_00pfOKSXTudGqfb');
    background-repeat: no-repeat;
    background-size: 70%70%;
    background-position: center center;
    background-color: blue;
}

Updated fiddle here.

Post a Comment for "How To Select Margin For A Background Image In Css/css3?"