CSS Div Background Image Fixed Height 100% Width
I’m trying to setup a series of div’s with a background image that each have their own fixed height, and stretch to fill up the width, even if there is overflow on the top/bottom that is clipped. I just don’t want the white space on the edges. Currently, I have: http://jsfiddle.net/ndKWN/ CSS
#main-container < float: left; width: 100%; margin: 0; padding: 0; text-align: center; >.chapter < position: relative; height: 1400px; z-index: 1; >#chapter1 < background: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg) 50% 0 no-repeat fixed; height: 1200px; >#chapter2 < background: url(http://download.ultradownloads.com.br/wallpaper/94781_Papel-de-Parede-Homer-Simpson--94781_1680x1050.jpg) 50% 0 no-repeat fixed; height: 1200px; >
The body padding and margin are both 0; The problem arises when you view the page on a browser with a width that exceeds the width of the image. The background image doesn’t fill horizontally.
3 Answers 3
See my answer to a similar question here.
It sounds like you want a background-image to keep it’s own aspect ratio while expanding to 100% width and getting cropped off on the top and bottom. If that’s the case, do something like this:
The problem with this approach is that you have the container elements at a fixed height, so there can be space below if the screen is small enough.
If you want the height to keep the image’s aspect ratio, you’ll have to do something like what I wrote in an edit to the answer I linked to above. Set the container’s height to 0 and set the padding-bottom to the percentage of the width:
You could also put the padding-bottom percentage into each #chapter style if each image has a different aspect ratio. In order to use different aspect ratios, divide the height of the original image by it’s own width, and multiply by 100 to get the percentage value.
Fit background image to div
You can achieve this with the background-size property, which is now supported by most browsers.
To scale the background image to fit inside the div:
To scale the background image to cover the whole div:
If what you need is the image to have the same dimensions of the div, I think this is the most elegant solution:
If not, the answer by @grc is the most appropriated one.
@Learner If you change the dimensions of a image without cropping the image the aspect ratio will be lost 99% of the time. It’s common sense.
You can use this attributes:
background-size: contain; background-repeat: no-repeat;
and you code is then like this:
background-position-x: center; background-position-y: center;
Welcome to stackoverflow! Please explain your answer to make it helpful. stackoverflow.com/help/how-to-answer stackoverflow.com/tour
background-size:contain; height: 0; width: 100%; padding-top: 66,64%;
I don’t know your div-values, but let’s assume you’ve got those.
height: auto; max-width: 600px;
Again, those are just random numbers. It could quite hard to make the background-image (if you would want to) with a fixed width for the div, so better use max-width. And actually it isn’t complicated to fill a div with an background-image, just make sure you style the parent element the right way, so the image has a place it can go into.
Link to a highly voted answer that talks about this solution in more detail: stackoverflow.com/questions/600743/… and shows you how to calculate the padding-top .
background-size: contain; background-size: cover; background-size: 100%; .container
The background-size property specifies the size of the background images.
There are different syntaxes you can use with this property: the keyword syntax («auto», «cover» and «contain»), the one-value syntax (sets the width of the image (height becomes «auto»), the two-value syntax (first value: width of the image, second value: height).
- percentage — Sets the width and height of the background image in percent of the parent element.
- cover — Resize the background image to cover the entire container, even if it has to stretch the image or cut a little bit off one of the edges
- contain — Resize the background image to make sure the image is fully visible
Scale div to fit background image
I have a div with a background image that I want to expand 100% width and auto scale the div to fit the required height of the image. At the moment it is not scaling the div height unless I set the height of the div to 100% but then it just stretches to the full height of the screen, whereas I want it to scale to the height of the image. Here is the html:
You want the width to be 100% of the browser window but the height to be limited to the height of the image? Are the proportions of the image known/consistent?
No, there is no way to set the div size, to dynamically use the same dimensions of the background image, using only CSS. You either need to insert the background image as it’s own image element or use Javascript to calculate the dimensions of the image and apply them to the div.
4 Answers 4
Let a transparent image dictate the DIV dimensions.
Inside that div put the same image with CSS opacity: 0
#mainHeaderWrapper < background: no-repeat url(path/to/image.jpg) 50% / 100%; >#mainHeaderWrapper img < vertical-align: top; width: 100%; /* max width */ opacity: 0; /* make it transparent */ >
That way the height of the DIV will be dictated by the containing invisible image, and having the background-image set to center, full ( 50% / 100% ) it will match that image’s proportions.
Need some content inside that DIV?
Due to the containing image, you’ll need an extra child element that will be set to position: absolute acting as an overlay element
#mainHeaderWrapper < position: relative; background: no-repeat url(path/to/image.jpg) 50% / 100%; >#mainHeaderWrapper > img < vertical-align: top; width: 100%; /* max width */ opacity: 0; /* make it transparent */ >#mainHeaderWrapper > div
Thanks, i was wondering how i was going to add content inside that div, so your second part of the answer has helped greatly.
If you know the proportions of the image, use percentage padding to define the height of the container. Set height:0 and set vertical padding to a percentage of the width.
They key to this method is that percentage-based vertical padding is always related to width.
The percentage is calculated with respect to the width of the generated box’s containing block, even for ‘padding-top’ and ‘padding-bottom’.
Below, the image is 400px X 200px, so the proportion of height to width is 1:2 and padding-top is set to 50%;
In another example, the image is 300px X 100px. The height is ⅓ of the width, so the padding-top is set to 33.33%:
Edit:
As prompted by Paulie_D, other content in the div must be positioned absolutely, demonstrated below. I suggest positioning these elements using percentages, as well.
#mainHeaderWrapper < width: 100%; height: 0; padding-top: 33.33%; background-image: url('https://dummyimage.com/300x100/'); background-size: 100% auto; background-repeat: no-repeat; >div#inner_content
Hello World stuff below the image
Высота блока по фоновой картинке
Надпись на фоновой картинке
Здравствуйте! Подскажите как делаются такие кнопки? У меня есть картинки пустые без надписи.
Map на фоновой картинке — реально ли?
Я сделал map- области ссылки на картинке. Картинка на всю ширину экрана, таким образом если.
как сделать ссылку на корневую папку на всей фоновой картинке на сайте
Я далек от web программирования, но пока приходится сайт вести самому. Подскажите, как сделать.
Если картинка вставлена через бэкграунд то только задавать размеры блоку или увеличивать его контентом
AlexZaw, я это знаю, но если вдруг я захочу поменять картинку, а размер будет другим, и картинка допустим будет меньше, чтото пойдет не так. я думал что можно при загрузке onload на js можно получать размеры картинки, а потом ставить высоту блока
если точнее то идет так, то вот картинку сделал
если я зделаю падинг для блока +50% фон зайдет, но вот текст пойдет ниже=\
если я знаю размер блока, то проблем нет. но вот если я не буду задавать размер блока, я могу задать размер по тексту, но вот как сделать по картинке, вот такая вот задачка
div>Lorem ipsum dolor sit amet consectetur adipisicing elit. Sit ducimus aliquid fuga nesciunt, doloribus facilis voluptates harum esse eveniet fugiat error, quas atque quos dignissimos sapiente molestias tenetur aperiam ipsum. Lorem ipsum dolor sit amet consectetur adipisicing elit. Sit ducimus aliquid fuga nesciunt, doloribus facilis voluptates harum esse eveniet fugiat error, quas atque quos dignissimos sapiente molestias tenetur aperiam ipsum./div>
div{display:inline-block;width:600px;background:url(https://dummyimage.com/1000x400/03b4e0/000000.png) no-repeat;background-size:100% 100%;}
Сообщение было отмечено DeMark229 как решение
Решение
#site_logo { width: 100%; height: 0; background-image: url(../image/logo.png); background-repeat: no-repeat; background-size: contain; padding-top: 25%; }
Универсального решения нет и быть не может, если динамически могут меняться размеры картинки и/или текста, то в любом случае возникнет ситуация когда либо картинка меньше чем блок с текстом, либо текст меньше чем картинка. Если во втором случае еще можно с помощью php или js получить размер картинки и задать блоку min-height , то когда картинка меньше чем контент, тут уже только не допускать таких ситуаций или отказаться от данного варианта.
А чем не устраивает вариант с img и абсолютным позиционирование блока с текстом поверх блока с картинкой?