How to Circumscribe a square in a circle CSS [duplicate] - css

I've looked into this a fair bit but can't seem to find a good, solid answer to find how to make a responsive circle around a div element of variable height.
It's easy to make a simple responsive circle using vw units.
<div style="height:20vw; width:20vw"></div>
However, I'm looking to use a min-height of an element and have a circle around this div.
Another way to create a responsive circle is using something like the snippet below, but again I can't adapt this to work for a variable height (again, I can't use vh units as the div will change in height.
.square {
position: relative;
width: 10%;
background: gray;
border-radius: 50%;
}
.square:after {
content: "";
display: block;
padding-bottom: 100%;
}
.content {
position: absolute;
width: 100%;
height: 100%;
}
<div class="square">
<div class="content">
</div>
</div>
I am trying to create something like the below, where the circle will never cut into the corners of the div (with around a 10px padding). I personally was trying to avoid javascript and would have preferred a css only approach, but it seems it's unavoidable. Maybe the only solution is to use a jquery to calculate the height of the element in order to apply this to a wrapper element?
I was playing around with this:
.square {
position: absolute;
top: 50%;
display: inline-block;
left: 50%;
transform: translate(-50%, -50%);
min-height: 100px;
border-radius: 50%;
background: url('https://i.imgur.com/2dxaFs9_d.webp?maxwidth=640&shape=thumb&fidelity=medium');
background-size: 100% 100%;
padding: 20px;
}
.content {
width: 300px;
min-height: 100px;
background: tomato;
}
<div class="square">
<div class="content">
Hello!<br>
<br><br><br>This has a variable height but fixed width<br><br><br>Hello
</div>
</div>

Clip-path can easily do this if you consider solid coloration.
Resize the element and the circle will follow:
.box {
width: 200px;
height: 200px;
overflow: hidden;
resize: both;
background: blue;
box-shadow: 0 0 0 200vmax red;
clip-path: circle(71%);
margin: 100px auto;
}
<div class="box"></div>
Related question to understand the magic number 71%: clip-path:circle() radius doesn't seem to be calculated correctly
To use an image we can consider pseudo elements. You can also rely on calc() to add the offset:
.box {
width: 200px;=
resize: both;
clip-path: circle(calc(71% + 10px));
margin: 100px auto;
position: relative;
font-size:35px;
color:#fff;
}
/* the background layer */
.box::before {
content:"";
position: absolute;
z-index:-1;
top:0;
left:0;
right:0;
bottom:0;
background:blue;
}
/* the image layer */
.box::after {
content:"";
position: fixed; /* to make sure the image cover all the screen */
z-index:-2;
top:0;
bottom:0;
left:0;
right:0;
background:url(https://picsum.photos/id/1015/1000/1000) center/cover no-repeat;
}
<div class="box" contenteditable="true"> Edit this<br>text </div>

I tried my hardest to figure this out with pure css. Though the problem with css I could not figure out how to calculate the diameter of the circle based on the content div size; the length from top left corner to bottom right corner of the variable height div.
I'm not sure if can be done using the calc() css function.
But I did manage to do it with a little jquery (which could easily be changed to pure javascript if you are not using jquery).
See working resizable example below (follow my comments in code)
Note: If you are using internet explorer the resizable demo content div will not resize.
// circumscriber for variable size divs
function circumscriber() {
// for each variable size div on page
$(".variable-size").each(function() {
// get the variable size div content width and height
let width = $(this).outerWidth();
let height = $(this).outerHeight();
// get the diameter for our pefect circle based on content size
let diameter = Math.sqrt(width ** 2 + height ** 2);
// extra 15 pixel circle edge around variable size div
let edge = 15;
// add current circle size width css
$('.circle', this).css({
'width': (diameter + (edge * 2)) + 'px'
})
});
}
// run the circumscriber (you might wana do this on ready)
circumscriber();
// if the window is resized responsively
$(window).on('resize', function() {
circumscriber();
});
// for demo purpose to fire circumscriber when resizing content
// not needed for real thing
$('.content').on('input', function() {
this.style.height = "";
this.style.height = ( this.scrollHeight - 30 ) + "px";
circumscriber();
}).on('mouseup', function() {
circumscriber();
});
/* variable size container to be circumscribed by circle */
/* none of these styles are required, this just to center the variable size div in the window for demo purposes */
.variable-size {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* resizable text area for demo */
/* again not needed */
.variable-size .content {
padding: 15px;
background: #fff;
resize: both;
overflow: auto;
color: #000;
border: none;
width: 200px;
font-weight: bold;
}
.variable-size .content:focus {
outline: 0;
}
/* child circle div css */
.variable-size .circle {
position: absolute;
background-image: url('https://i.imgur.com/2dxaFs9_d.webp?maxwidth=640&shape=thumb&fidelity=medium');
background-position: center center;
z-index: -1;
border-radius: 50%;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
transition: all 0.5s ease;
width: 0;
}
/* fast way to make circle height the same as current width */
.variable-size .circle:before {
display: block;
content: '';
width: 100%;
padding-top: 100%;
}
/* demo window css */
HTML,
BODY {
height: 100%;
min-height: 100%;
background: black;
position: relative;
font-family: "Lucida Console", Courier, monospace;
}
<div class="variable-size">
<textarea class="content" rows="1" placeholder="TYPE TEXT OR RESIZE ME ↘"></textarea>
<div class="circle"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
See jsfiddle here... https://jsfiddle.net/joshmoto/6d0zs7uq/

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.stroke();
Source: https://www.w3schools.com/

You could use flex display and insert empty flex-items around the inner div and use flex-basis to fix their width.
Try this
.square {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
min-height: 100px;
border-radius: 50%;
background: black;
background-size: 100% 100%;
padding: 20px;
}
.content {
width: 300px;
min-height: 100px;
background: tomato;
}
.emptyDiv {
flex-basis: 120px
}
<div class="square">
<div class="emptyDiv"></div>
<div class="content">
Hello!<br>
<br><br><br>This has a variable height but fixed width<br><br><br>Hello
</div>
<div class="emptyDiv"></div>
</div>

Related

css transparent shape over image

This is what i am trying to achive
i have :
#image1 {
position: absolute;
bottom: 0px;
align-self: auto;
background-color: #dc022e;
width: 340px;
height: 100px;
border-radius: 50% / 100%;
border-bottom-left-radius: 0;
/*transform: rotate(10deg);*/
border-bottom-right-radius: 0;
opacity: 0.8;
}
#image2 img {
width: 80%;
}
<div>
<div id="image2">
<img src="http://t1.gstatic.com/images?q=tbn:ANd9GcThtVuIQ7CBYssbdwtzZjVLI_uw09SeLmyrxaRQEngnQAked5ZB">
</div>
<div id="image1"></div>
</div>
Finally I don't know how to make it rotated and with the margins cut like in the picture
A Quick example of this would use a pseudo element and have the image set in the background.
div {
position: relative;
height: 300px;
width: 500px;
background: url(http://lorempixel.com/500/300);/*image path*/
overflow: hidden;/*hides the rest of the circle*/
}
div:before {
content: "";
position: absolute; /*positions with reference to div*/
top: 100%;
left: 50%;
width: 0;/*define value if you didn't want hover*/
height: 0;
border-radius: 50%;
background: tomato;/*could be rgba value (you can remove opacity then)*/
opacity: 0.5;
transform: translate(-50%, -50%);/*ensures it is in center of image*/
transition: all 0.4s;
}
/*Demo Only*/
div:hover:before {/*place this in your pseudo declaration to remove the hover*/
height: 100%;
width: 150%;/*this makes the shape wider than square*/
transform: translate(-50%, -50%) rotate(5deg);/*ensures it is in center of image + rotates*/
}
div {/*This stuff is for the text*/
font-size: 40px;
line-height: 300px;
text-align: center;
}
<div>HOVER ME</div>
Instead of nested elements, you can just use a pseudo element. This is placed at the bottom of the container div. For this to work, you need position:relative and overflow:hidden on the container div. Also, pseudo elements always need the content declaration.
To modify the border radius, you just play around with left | width | height of the pseudo element. You don't need any rotation.
Instead of hex color and opacity you can as well use the "new" color space rgba(r,g,b,a) where a is the opacity value.
For the passepartout you simply use the border declaration.
#image2{
position:relative;
border:10px solid #888;
overflow:hidden;
box-shadow:0 0 4px #aaa;
}
#image2::after {
content:"";
display:block;
position: absolute;
bottom: 0;left:-10%;
background-color: #dc022e;
width: 120%;
height: 60%;
border-radius: 100% 100% 0 0;
opacity: 0.8;
}
#image2 img {
width: 100%;
display:block;
position:relative;
}
<div id="image2">
<img src="http://t1.gstatic.com/images?q=tbn:ANd9GcThtVuIQ7CBYssbdwtzZjVLI_uw09SeLmyrxaRQEngnQAked5ZB">
</div>
You can just use position: absolute for your image and position: relative for your overlay, adjusting the top position and width according to your needs. Here's a Fiddle. Hope this helps!
Edit: Here's an updated version of the Fiddle demonstrating border and overflow properties on the img container. As CBroe mentioned, rotating a circle is probably not a good use of your time in this case. Also, I definitely agree that using a pseudo element is a much cleaner approach than nesting images.

cannot center and crop image inside a div box [duplicate]

I know that it is impossible to actually modify an image with CSS, which is why I put crop in quotes.
What I'd like to do is take rectangular images and use CSS to make them appear square without distorting the image at all.
I'd basically like to turn this:
Into this:
A pure CSS solution with no wrapper div or other useless code:
img {
object-fit: cover;
width: 230px;
height: 230px;
}
Assuming they do not have to be in IMG tags...
HTML:
<div class="thumb1">
</div>
CSS:
.thumb1 {
background: url(blah.jpg) 50% 50% no-repeat; /* 50% 50% centers image in div */
width: 250px;
height: 250px;
}
.thumb1:hover { YOUR HOVER STYLES HERE }
EDIT: If the div needs to link somewhere just adjust HTML and Styles like so:
HTML:
<div class="thumb1">
Link
</div>
CSS:
.thumb1 {
background: url(blah.jpg) 50% 50% no-repeat; /* 50% 50% centers image in div */
width: 250px;
height: 250px;
}
.thumb1 a {
display: block;
width: 250px;
height: 250px;
}
.thumb1 a:hover { YOUR HOVER STYLES HERE }
Note this could also be modified to be responsive, for example % widths and heights etc.
If the image is in a container with a responsive width:
.rect-img-container {
position: relative;
}
.rect-img-container::after {
content: "";
display: block;
padding-bottom: 100%;
}
.rect-img {
position: absolute;
width: 100%;
height: 100%;
object-fit: cover;
}
<div class="rect-img-container">
<img class="rect-img" src="https://picsum.photos/id/0/367/267" alt="">
</div>
(edit: updated from sass to plain css)
(edit: Added dummy image for reference)
Place your image in a div.
Give your div explicit square dimensions.
Set the CSS overflow property on the div to hidden (overflow:hidden).
Put your imagine inside the div.
Profit.
For example:
<div style="width:200px;height:200px;overflow:hidden">
<img src="foo.png" />
</div>
Using background-size:cover - http://codepen.io/anon/pen/RNyKzB
CSS:
.image-container {
background-image: url('http://i.stack.imgur.com/GA6bB.png');
background-size:cover;
background-repeat:no-repeat;
width:250px;
height:250px;
}
Markup:
<div class="image-container"></div>
I actually came across this same problem recently and ended up with a slightly different approach (I wasn't able to use background images). It does require a tiny bit of jQuery though to determine the orientation of the images (I' sure you could use plain JS instead though).
I wrote a blog post about it if you are interested in more explaination but the code is pretty simple:
HTML:
<ul class="cropped-images">
<li><img src="http://fredparke.com/sites/default/files/cat-portrait.jpg" /></li>
<li><img src="http://fredparke.com/sites/default/files/cat-landscape.jpg" /></li>
</ul>
CSS:
li {
width: 150px; // Or whatever you want.
height: 150px; // Or whatever you want.
overflow: hidden;
margin: 10px;
display: inline-block;
vertical-align: top;
}
li img {
max-width: 100%;
height: auto;
width: auto;
}
li img.landscape {
max-width: none;
max-height: 100%;
}
jQuery:
$( document ).ready(function() {
$('.cropped-images img').each(function() {
if ($(this).width() > $(this).height()) {
$(this).addClass('landscape');
}
});
});
Check out CSS aspect-ratio
https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio
.square-image{
width: 50%;
background-image: url('https://picsum.photos/id/0/367/267');
background-size: cover;
background-position: center;
aspect-ratio: 1/1;
}
<div class="square-image"></div>
You can also do this with a regular img tag as follows
.square-image{
width: 50%;
object-fit: cover; /* Required to prevent the image from stretching, use the object-position property to adjust the visible area */
aspect-ratio: 1/1;
}
<img src="https://picsum.photos/id/0/367/267" class="square-image"/>
Today you can use aspect-ratio:
img {
aspect-ratio: 1 / 1;
}
It has wide support amongst modern browsers as well:
https://caniuse.com/mdn-css_properties_aspect-ratio
object-fit: cover will do exactly what you need.
But it might not work on IE/Edge. Follow as shown below to fix it with just CSS to work on all browsers.
The approach I took was to position the image inside the container with absolute and then place it right at the centre using the combination:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
Once it is in the centre, I give to the image,
// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;
// For Horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;
This makes the image get the effect of Object-fit:cover.
Here is a demonstration of the above logic.
https://jsfiddle.net/furqan_694/s3xLe1gp/
This logic works in all browsers.
Original Image
Vertically Cropped
Horizontally Cropped
Square Container
I had a similar issue and could not "compromise" with background images.
I came up with this.
<div class="container">
<img src="http://lorempixel.com/800x600/nature">
</div>
.container {
position: relative;
width: 25%; /* whatever width you want. I was implementing this in a 4 tile grid pattern. I used javascript to set height equal to width */
border: 2px solid #fff; /* just to separate the images */
overflow: hidden; /* "crop" the image */
background: #000; /* incase the image is wider than tall/taller than wide */
}
.container img {
position: absolute;
display: block;
height: 100%; /* all images at least fill the height */
top: 50%; /* top, left, transform trick to vertically and horizontally center image */
left: 50%;
transform: translate3d(-50%,-50%,0);
}
//assuming you're using jQuery
var h = $('.container').outerWidth();
$('.container').css({height: h + 'px'});
Hope this helps!
Example:
https://jsfiddle.net/cfbuwxmr/1/
Use CSS: overflow:
.thumb {
width:230px;
height:230px;
overflow:hidden
}
Either use a div with square dimensions with the image inside with the .testimg class:
.test {
width: 307px;
height: 307px;
overflow:hidden
}
.testimg {
margin-left: -76px
}
or a square div with a background of the image.
.test2 {
width: 307px;
height: 307px;
background: url(http://i.stack.imgur.com/GA6bB.png) 50% 50%
}
Here's some examples: http://jsfiddle.net/QqCLC/1/
UPDATED SO THE IMAGE CENTRES
.test {
width: 307px;
height: 307px;
overflow: hidden
}
.testimg {
margin-left: -76px
}
.test2 {
width: 307px;
height: 307px;
background: url(http://i.stack.imgur.com/GA6bB.png) 50% 50%
}
<div class="test"><img src="http://i.stack.imgur.com/GA6bB.png" width="460" height="307" class="testimg" /></div>
<div class="test2"></div>
I came with a different approach. You basically have to crop the rectangular image to fit it inside the square is all there is to it. Best approach is if the image width is greater than the height, then you crop the image alittle from left and right side of the image. If the image height is greater than the image width then you crop the bottom of the image. Here is my solution. I needed a little help from PHP though.
<div style="position: relative; width: 154px; height: 154px; overflow: hidden;">
<?php
//get image dimmensions whichever way you like. I used imgaick
$image = new Imagick("myimage.png");
$width = $image->getImageWidth();
$height = $image->getImageHeight();
if($width > $height){
?>
<img src="myimage.png" style="display: block; position: absolute; top: 0px; left: 50%; transform: translateX(-50%); -ms-transform: translateX(-50%); -webkit-transform: translateX(-50%); height: 100%; " />
<?php
}else{
?>
<img src="myimage.png" style="display: block; position: absolute; top: 0px; left: 0px; width: 100%; " />
<?php
}
?>
</div>

Circular button that resizes with window size

I'd like to make a circular button (div works too) and put it in the centre with a diameter of 20% of the height of the window. This I can do, but the button will become oval if the window isn't exactly square (I'd like the width and height to be the same - a perfect circle).
.circle {
height: 20%;
width: 20%;
border-radius: 100%;
font-size: 20px;
color: #fff;
line-height: 100px;
text-align: center;
background: #000
}
Hardcoding a pixel value isn't much of an option as it wouldn't resize based on the window. Any ideas?
There are two ways to achive this; with and without JavaScript.
The JavaScript method
Here's a simple demo: little link.
HTML:
<div class = "circle"></div>
CSS:
html, body {
height: 100%;
}
.circle {
border-radius: 1000px;
background-color: rgb(0, 162, 232);
}
JavaScript (uses jQuery, but it isn't necessary):
function upd() {
var h = $("body").height();
$(".circle").height(h / 5);
$(".circle").width(h / 5);
}
upd();
window.onresize = upd;
The non-JavaScript (CSS) method
For a CSS-only solution, you need to use the fact that all padding values are calculated relative to the element parent's width, not height (reference). Little demo: little link.
HTML:
<div class = "wrapper">
<div class = "main">
</div>
</div>
CSS:
html, body {
height: 100%;
width: 100%;
}
.wrapper {
width: 20%;
display: inline-block;
position: relative;
}
.wrapper:after {
padding-top: 100%; /*1:1 ratio*/
display: block;
content: '';
}
.main {
position: absolute;
top: 0; bottom: 0; right: 0; left: 0; /*fill parent*/
border-radius: 1000px;
background-color: rgb(0, 162, 232);
/*I wanted it to look good :)*/
font-family: 'Arial', Helvetica, Sans-Serif;
color: white;
}
There is a way to achieve a perfect circle without using any JS, it lies in the specifications definition for padding percentage. When the padding is applied as a percentage it is applied as a percentage of the objects width, which means if you set width and height to 0, and give the object a padding of 20% you'll end up with a circle occupying 20% of the available width. You'll need to get creative to get things inside the circle though.
<style>
html, body {
width:80%;
}
.square
{
width:0%;
height:0%;
padding:20%;
position:relative;
left:25%;/*Position central*/
border-radius:100%;
margin:auto;/*Position central*/
border:1px solid #000000;
}
</style>
The easiest fix is to add min-height and min-width property to that circle with same value.
.circle {
min-width: 100px;
min-height: 100px;
}

fixed size centered div surrounded by expanding divs

I am working on a website and the client wants to have something similar to this: http://www.csszengarden.com/?cssfile=202/202.css
There are several overlays that are attached to the edges of the screen, while the text in the center is contained in such a way that the original browser scroll bars remain usable. This design is made elastic by allowing it to stretch at least vertically through an extra div.
The tricky part about my design: I have a fixed size div that is supposed to be centered both vertically and horizontally. What I need now are further divs that surround the centered div and expand as the user resizes their window, in order to serve as overlays to hide the text below them.
This is basically it: http://imgur.com/TNaTU
So broken down even further, what I need is a way to have the four surrounding divs automatically expand or reduce their size so they always fill up all of the screen.
Is there a way to do this without Javascript?
This won't work in IE7 without some crazy hacks, because IE7 does not support display: table and friends.
I will have a look at making this work in IE7 if it's a requirement for you.
Tested in IE8 and recent versions of Firefox, Chrome, Safari, Opera.
Live Demo (edit)
HTML:
<div id="top">top stretch</div>
<div id="middle">
<div id="middleContainer">
<div class="stretch">left stretch</div>
<div id="fixed">fixed</div>
<div class="stretch">right stretch</div>
</div>
</div>
<div id="bottom"><div id="bottomContent">bottom stretch</div></div>
CSS:
html, body {
margin: 0;
padding: 0;
height: 100%;
overflow: hidden
}
#top, #bottom {
position: absolute;
left: 0;
right: 0;
text-align: center
}
#top {
top: 0;
height: 50%
}
#bottom {
bottom: 0;
height: 50%
}
#bottomContent { /* you don't need this if bottom won't hold "content" */
position: absolute;
right: 0; bottom: 0; left: 0
}
#fixed {
width: 400px
}
#middle {
background: #ee1c24;
position: absolute;
width: 100%;
height: 300px;
top: 50%;
margin-top: -150px; /* height/2 */
left: 0;
z-index: 1
}
#middleContainer {
display: table;
width: 100%;
height: 100%
}
.stretch, #fixed {
display: table-cell
}
/* just for demo */
#top, #bottom, .stretch {
background: #b5e61d;
border: 5px solid #000
}
#fixed {
border-top: 5px solid #000;
border-bottom: 5px solid #000
}

How do I center an image if it's wider than its container?

Normally, you center images with display: block; margin: auto, but if the image is larger than the container, it overflows to the right. How do I make it overflow to the both sides equally? The width of the container is fixed and known. The width of the image is unknown.
A pure css solution
Requiring one extra wrapper (tested in FireFox, IE8, IE7):
Improved Answer
There was a problem with the original answer (below). If the image is larger than the container that outer is centered on with it's auto margins, then it truncates the image on the left and creates excessive space on the right, as this fiddle shows.
We can resolve that by floating inner right and then centering from the right. This still truncates the img off the page to the left, but it does so by explicitly pushing it that way and then centers back off of that, the combination of which is what prevents the extra horizontal scroll on the right. Now we only get as much right scroll as we need in order to see the right part of the image.
Fiddle Example (Borders in fiddle are for demo only.)
Essential CSS
div.outer {
width: 300px; /* some width amount needed */
margin: 0 auto;
overflow: visible;
}
div.inner {
position:relative;
float: right; /* this was added and display removed */
right: 50%;
}
div.inner img {
position: relative;
right:-50%; /* this was changed from "left" in original */
}
If you desire no right scroll at all for wide images
Then using the above, also set whatever element wraps outer (like body or a third wrapper) to have overflow: hidden.
Original Idea (for History)
Fiddle Example (Borders in fiddle are for demo only.)
HTML
<div class="outer">
<div class="inner">
<img src="/yourimage.png">
</div>
</div>
CSS
div.outer {
width: 300px; /* some width amount needed */
margin: 0 auto;
overflow: visible;
}
div.inner {
display: inline-block;
position:relative;
right: -50%;
}
div.inner img {
position: relative;
left:-50%;
}
Here's a 2 line CSS solution (a couple more lines might be required for cross-browser support):
img {
margin-left: 50%;
transform: translateX(-50%);
}
HTML
​<div class="image-container">
<img src="http://www.google.com/images/logo.gif" height="100" />
</div>​
CSS
.image-container {
width: 150px;
border: solid 1px red;
margin:100px;
}
.image-container img {
border: solid 1px green;
}
jQuery
$(".image-container>img").each(function(i, img) {
$(img).css({
position: "relative",
left: ($(img).parent().width() - $(img).width()) / 2
});
});
​
See it on jsFiddle: http://jsfiddle.net/4eYX9/30/
Alternative pure CSS solution is to use transform attribute:
HTML:
<div class="outer">
<img class="image" src="http://www.gstatic.com/webp/gallery/4.jpg" />
</div>
CSS:
.outer {
position: relative;
width: 100px;
border: 1px solid black;
height: 150px;
margin-left: 100px; /* for demo */
/* overflow: hidden; */
}
img.image {
width: 200px;
opacity: 0.7;
position: absolute;
left: 50%;
transform: translateX(-50%);
-webkit-transform: translateX(-50%);
}
Fiddle
Just to add a overflow:hidden to parent div to hide the extra area of the image.
Your best bet is to set it as background image of the container instead.
#container {
background: url('url/to/image.gif') no-repeat center top;
}
In fact there is a simpler pure css/html way (without large horizontal scroll) :
Html :
<div class="outer">
<img src="/my/sample/image.jpg">
</div>
Css :
If you don't want to see image overflow
div.outer img {
position: absolute;
left: -50%;
z-index:-1;
}
div.outer {
overflow: hidden;
position: relative;
height: 200px;
}
With image overflow visible
div.outer img {
position: absolute;
left: -50%;
z-index:-1;
}
div.outer {
overflow: visible;
position: relative;
height: 200px;
}
body, html {
overflow-x:hidden;
}
A background solution with image overflow visible :
Html :
<div class="outer">
<div class="inner"></div>
</div>
Css :
div.outer {
width: 100%;
height: 200px;
}
div.inner {
background: url('/assets/layout/bg.jpg') center no-repeat;
position: absolute;
left: 0;
width: 100%;
height: inherit;
}
assuming outer is in a width specified container.
I see this is an old post, so maybe everybody knows this by now, but I needed help for this and I solved it using flex:
.parent {
display: flex;
/* give it the width and height you like */
}
.parent img {
min-width: 100%;
min-height: 100%;
object-fit: cover;
}
I can only think of a Javascript solution since what you need to do is relatively position the image a negative amount to the left of its container:
jQuery
$(document).ready(function(){
var theImg = $('#container img');
var theContainer = $('#container');
if(theImg.width() > theContainer.width()){
theImg.css({
position: 'relative',
left: (theContainer.width() - theImg.width()) / 2
})
}
})
I found this to be a more elegant solution, without flex, similar to something above, but more generalized (applies on both vertical and horizontal):
.wrapper {
overflow: hidden;
}
.wrapper img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
/* height: 100%; */ /* optional */
}
I don't think there is a pure CSS solution (Except for the next answer :)). However with Javascript it would be just a matter of finding the width of the image, subtracting the container width, dividing by two and you have how far to the left of the container you need.

Resources