开发者

Media Query-like behaviour on width of a specific div

I'm building an editor where the content of a post is loaded in a div, and jQuery selectors allow me to edit the content inline.

I just ran into a bit of a hurdle as I was trying to add some responsiveness to the styling of the templates: in my template stylesheets, I use a specific id of the preview area to specify where the style should apply. I apply the same id to the body tag of the viewing of the post so that both the preview in the editor and the full view of the post look the same.

I was putting in some media queries on the view side of things and realized that on the preview page, something like @media screen and (max-width: 640px) will behave differently because the preview does not take up the entire width of the screen.

Is there a way I can use a medi开发者_如何学Pythona query selector other than the width of the screen, but instead the width of an element.. or something equivalent? Or could there be another way of mimicking that behaviour simply with javascript..


Unfortunately there is not currently a way for a media query to target a div. Media queries can only target the screen, meaning the browser window, mobile device screen, TV screen, etc...


Update (2018):

This is still a common problem for many developers. There is no way without javascript to query the size of an element. It's also very difficult to implement in CSS because of the 'cyclic dependencies' it causes (element relies on another to determine its size, element query causes size change in child which causes size change in parent which causes size change in child ETC...)

There is a great summary of the current element query landscape.

The go-to solution these days is the EQCss library https://github.com/eqcss/eqcss, or handling the changes within a javascript framework like React or Vue using a "CSSinJS" type solution.

My old and hilariously janky "solution":

For now I am using:

.preview {
    zoom: .8; 
    -moz-transform: scale(0.8);}

when the .preview div is 80% of the page width. It's generally working, but with a few issues, and it is not entirely flexible since the divs in question will not always be set % of the page width.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜